我不知道为什么最后一个断言不起作用。错误消息“类型对象'Student'没有属性'name'”,这使我更加困惑,因为Student具有名为name的属性。有解决方案吗?
class Student:
def __init__(self, name, imt_name, semester):
self.name = name
self.imt_name = imt_name
self.semester = semester
def get_name(self):
return self.name
def __str__(self):
return ("{} [{}] in Semester {}".format(self.name, self.imt_name, self.semester))
x = property(get_name)
#asserts and test
assert type(Student) is type
student_horst = Student("Horst", "horst99", 2)
assert student_horst.name == "Horst"
assert student_horst.imt_name == "horst99"
assert student_horst.semester == 2
student_horst.semester = 3
assert student_horst.semester == 3
#this one is not working!
assert isinstance(getattr(Student, "name"), property)
答案 0 :(得分:0)
要检查实例是否具有给定的属性(按名称),您需要使用hasattr
函数,如下所示:
startWith
答案 1 :(得分:0)
name从来不是属性,x是
class Student:
def __init__(self, name):
self._name = name # this is an attribute
@property
def name(self): # property
return self._name
def get_name(self):
return self._name
x = property(get_name) # x is a property not _name
student = Student('Horst')
print(student._name, student.name, student.x, sep='\n')
assert isinstance(getattr(Student, 'name'), property)
assert isinstance(getattr(Student, 'x'), property)