当前位置: 代码迷 >> 综合 >> python中类属性和实例属性的使用和区别
  详细解决方案

python中类属性和实例属性的使用和区别

热度:47   发布时间:2024-01-17 15:29:00.0

# 类属性和实例属性class Student:count = 10                              # count是类属性def __init__(self, name):self.name = name                    # name是实例属性print(Student.count)                        # 10 通过类来访问类属性
# print(Student.name)                         # 报错:AttributeError: type object 'Student' has no attribute 'name's1 = Student("xiaoming")
print(s1.name)                              # xiaoming 必须通过实例来访问实例属性name
print(s1.count)                             # 10 实例也可以访问类属性# 通过实例更改类属性的值,不影响类访问类属性的值s1.count = 50
print(s1.count)                             # 50 实例更改类属性的10为50
print(Student.count)                        # 10 通过类访问count的值,发现还是原来的10,并没有被改成50# 通过类更改类属性的值,不影响实例访问类属性的值Student.count = 33
print(s1.count)                             # 50 实例访问类属性值为上次更改的值50,不是类更改的值33
print(Student.count)                        # 33 类访问类属性的值是被更改的33# 另外实例化一个对象,其值不是默认值,而是上次由类更改类属性后的值s2 = Student("xiaohua")
print(s2.count)                             # 33 此处对象访问的count值为33,而不是默认值10,也不是之前由对象更改的值50
print(Student.count)                        # 33 这里也是33,而不是默认值10

 

  相关解决方案