如何在.txt文件中用Python编写对象属性

2024-06-02 05:48:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写simpe OOP程序。任务是在txt文件中写入对象的属性。我尝试了很多方法,但每次都得到了AttributeError: 'Message' object has no attribute 'self'。我已经改变了很多次,但是没有人帮我

class Message:
def __init__(self, id=10000000, subject='Title', text='Sample Text ', created_at='11.11.11', seen_at='11.11.11', support_group='sample text'):
    self.__id = id
    self.__subject = subject
    self.__text = text
    self.__created_at  = created_at
    self.__seen_at = seen_at
    self.__support_group = support_group
ms1 = Message(5775575, 'Order Telephone', 'The order is: Iphone 12 Pro Max 512 gb ', 'Created at: 
30.03.20', 'Seen at: 01.04.20', 'Account: Kim2030 \n Tech: Eldorado \n Billing: 5169147129584558 \n 
Order: 28048')
file = open('testfile.txt', 'w')

file.write(ms1.self.__id)
file.write(ms1.self.__subject)
file.write(ms1.self.__text)
file.write(ms1.self.__created_at)
file.write(ms1.self.__seen_at)
file.write(ms1.self.__support_group)

file.close()

Tags: textselftxtidsupportmessagegrouporder
1条回答
网友
1楼 · 发布于 2024-06-02 05:48:30

您使用的语法有点不正确。删除self引用,不要对变量前缀使用下划线:

class Message:
    def __init__(self, id=10000000, subject='Title', text='Sample Text ', created_at='11.11.11', seen_at='11.11.11',
                 support_group='sample text'):
        self.id = id
        self.subject = subject
        self.text = text
        self.created_at = created_at
        self.seen_at = seen_at
        self.support_group = support_group

ms1 = Message(5775575, 'Order Telephone', 'The order is: Iphone 12 Pro Max 512 gb ', 'Created at:30.03.20', 'Seenat: 01.04.20', 'Account: Kim2030 \nTech: Eldorado \nBilling: 5169147129584558 \nOrder: 28048')
file = open('testfile.txt', 'w')

file.write(str(ms1.id))
file.write(ms1.subject)
file.write(ms1.text)
file.write(ms1.created_at)
file.write(ms1.seen_at)
file.write(ms1.support_group)

file.close()

相关问题 更多 >