【发布时间】:2022-01-16 13:54:12
【问题描述】:
我正在尝试编写代码并使用 pytest 进行检查。我以为我做的一切都很好,但我遇到了问题。写完之后,我想用 Person 类的方法来检查它。当我尝试使用方法 id 时,函数结束并得到输出:
TypeError: 'str' object is not callable
我的代码:
class Person:
def __init__(self, id, name, sex, birth_date):
self.name = name
self.id = id
self.sex = sex
self.birth_date = birth_date
def __str__(self):
return f'{self.name} born {self.birth_date} with {self.sex} has {self.id}'
def name(self):
return self.name
def sex(self):
return self.sex
def id(self):
return self.id
def date_of_birth(self):
return self.birth_date
def read_from_file(file_handle):
people = []
reader = csv.DictReader(file_handle)
for row in reader:
id = row['id']
name = row['name']
sex = row['sex']
birth_date = row['birth_date']
person = Person(id, name, sex, birth_date)
print(person.id())[Error in this line]
people.append(person)
return people
def test_files():
with open('people.txt', 'r') as people_txt:
people = read_from_file(people_txt)
people.txt 行示例:
id,name,sex,birth_date
1,Doralyn Dovermann,Female,27/10/2005
2,Rickert Petschel,Male,10/7/2018
3,Whitney Girardoni,Female,7/3/1932
【问题讨论】:
-
错误信息指向哪一行?
-
请始终包含完整的 Traceback。将其格式化为代码。
-
缺少行号,也只是一个提示:您将 id 作为函数,然后在构造函数中将属性变量定义为
self.id,可能最好重命名其中一个以保留命名约定干净。 -
它的工作原理是这样的,因为您正在实例化
Person()类并将所有方法与它一起传递到定义的person。可能会研究继承和 OOP 主题。 -
您为方法使用的名称与用于它们应该返回的属性的名称相同。那是行不通的。像
person.id这样的属性查找只能找到属性或方法,不能同时找到两者(实例属性优先)。为什么要编写这些方法并不明显(Python 中通常不使用 getter 方法)。
标签: python csv file object typeerror