如何将Python父子类对象的属性写入TXT文件?
解决Python类对象写入TXT文件仅显示内存地址的问题
我编写了Python父子类程序:父类Staff接收4个字符串输入,子类TeachingStaff继承自Staff并接收6个字符串输入。尝试将用户输入生成的类对象转成字符串写入TXT文件时,文件里只显示对象的内存地址(比如<__main__.TeachingStaff object at 0x000001EAE84A1390>),不知道怎么把属性内容写入文件。原代码如下:
#define parent class class Staff: def __init__(self, fname, lname, dob, department): self.fname = fname self.lname = lname self.dob = dob self.department = department #define print function to print the parent class object def printsf(self): print(self.fname, self.lname, self.dob, self.department) #define child class class TeachingStaff(Staff): def __init__(self, fname, lname, dob, department, discipline, licenseNumber): super().__init__(fname, lname, dob, department) self.discipline = discipline self.licenseNumber = licenseNumber #define print function to print the child class object def printtsf(self): print(self.fname, self.lname, self.dob, self.department, self.discipline, self.licenseNumber) staffDetails = open("staffDetails.txt", "a") # open file for appending teachingDetails = open("teachingDetails.txt", "a") # open file for appending loopdobInput = input("Enter the date of birth in the format DD/MM/YYYY:") loopfnameInput = input("Enter first name:") looplnameInput = input("Enter last name:") loopdepartmentInput = input("Enter department name:") loopdecisionInput = input("Is the staff member a teacher (Y/N?") if loopdecisionInput == "y" or loopdecisionInput == "Y": loopdisiplineInput = input("Enter discipline:") looplicenceInput = input("Enter licence number:") loopteachingInput = TeachingStaff(loopdobInput, loopfnameInput, looplnameInput, loopdepartmentInput, loopdisiplineInput, looplicenceInput) loopteachingstr = str(loopteachingInput) teachingDetails.write(loopteachingstr) else: loopstaffInput = Staff(loopdobInput, loopfnameInput, looplnameInput, loopdepartmentInput) loopstaffstr = str(loopstaffInput) staffDetails.write(loopstaffstr) staffDetails.close() teachingDetails.close()
解决方案
问题根源是Python默认的str()实现会返回对象的内存地址,需要在类中自定义__str__方法,让对象转字符串时输出属性内容。同时优化代码结构,用with语句简化文件操作:
- 给父类
Staff添加__str__方法,返回属性拼接的字符串 - 给子类
TeachingStaff添加__str__方法,复用父类逻辑并拼接子类特有的属性 - 将外部打印函数改为类方法(符合面向对象规范)
- 使用
with语句自动管理文件,避免手动关闭遗漏
修改后的完整代码:
# 定义父类 class Staff: def __init__(self, fname, lname, dob, department): self.fname = fname self.lname = lname self.dob = dob self.department = department # 自定义__str__方法,返回属性内容 def __str__(self): return f"{self.fname}, {self.lname}, {self.dob}, {self.department}" # 类内的打印方法 def print_details(self): print(self.fname, self.lname, self.dob, self.department) # 定义子类 class TeachingStaff(Staff): def __init__(self, fname, lname, dob, department, discipline, licenseNumber): super().__init__(fname, lname, dob, department) self.discipline = discipline self.licenseNumber = licenseNumber # 自定义子类的__str__方法 def __str__(self): # 复用父类的__str__逻辑,拼接子类属性 return f"{super().__str__()}, {self.discipline}, {self.licenseNumber}" # 子类的打印方法 def print_details(self): print(self.fname, self.lname, self.dob, self.department, self.discipline, self.licenseNumber) # 处理用户输入 loopdobInput = input("Enter the date of birth in the format DD/MM/YYYY:") loopfnameInput = input("Enter first name:") looplnameInput = input("Enter last name:") loopdepartmentInput = input("Enter department name:") loopdecisionInput = input("Is the staff member a teacher (Y/N)?") if loopdecisionInput.lower() == "y": loopdisiplineInput = input("Enter discipline:") looplicenceInput = input("Enter licence number:") # 注意参数顺序:原代码中把dob放在了第一个,和类的__init__参数顺序不符,这里修正了 loopteachingInput = TeachingStaff(loopfnameInput, looplnameInput, loopdobInput, loopdepartmentInput, loopdisiplineInput, looplicenceInput) # 调用自定义__str__方法转字符串,写入文件时加换行符分隔记录 with open("teachingDetails.txt", "a") as teachingDetails: teachingDetails.write(str(loopteachingInput) + "\n") else: loopstaffInput = Staff(loopfnameInput, looplnameInput, loopdobInput, loopdepartmentInput) with open("staffDetails.txt", "a") as staffDetails: staffDetails.write(str(loopstaffInput) + "\n")
关键说明
__str__是Python特殊方法,调用str(obj)或打印对象时会自动触发,自定义后可返回指定格式的属性字符串super().__str__()复用父类的字符串生成逻辑,减少代码重复with语句会在代码块结束后自动关闭文件,比手动调用close()更安全- 写入时添加
\n换行符,让每条记录单独占一行,方便后续读取
内容的提问来源于stack exchange,提问作者Phillip Handfield
相关产品推荐
相关产品推荐

