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

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑟寒凌风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值