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


# 类属性和实例属性


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

猜你喜欢

转载自blog.csdn.net/sehanlingfeng/article/details/92415782