属性 似乎不正确

Property does not seem to work the right way

我不明白为什么最后一个断言不起作用。错误消息 "type object 'Student' has no attribute '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)

要检查实例是否具有给定的属性(按名称),您需要使用 hasattr 函数,如下所示:

assert hasattr(student_horst, "name")

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)