由于Python是动态语言,根据类创建的实例可以任意绑定属性。

给实例绑定属性的方法是通过实例变量,或者通过self变量:

class Student(object):
    def __init__(self, name):
        self.name = name

s = Student('Bob')
s.score = 90

但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归Student类所有:

class Student(object):
    name = 'Student'

当我们定义了一个类属性后,这个属性虽然归类所有,但类的所有实例都可以访问到。

s = Student()
print(s.name) #Student
print(Student.name)#Student
s.name = 'Michael'
print(s.name) #Michael
print(Student.name) #Student

在编写程序的时候,千万不要对实例属性和类属性使用相同的名字,因为相同名称的实例属性将屏蔽掉类属性。

相关文章:

  • 2022-12-23
  • 2021-12-10
  • 2021-05-19
  • 2022-12-23
  • 2021-05-29
  • 2021-07-27
  • 2021-12-19
猜你喜欢
  • 2022-02-21
  • 2022-12-23
  • 2021-08-23
  • 2019-02-11
  • 2021-05-16
  • 2021-09-14
  • 2022-02-28
相关资源
相似解决方案