python类属性

参考教程:

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014319117128404c7dd0cf0e3c4d88acc8fe4d2c163625000

测试代码:

class Student(object):
    count=0
    print("the first time to create an object of Student")
    def __init__(self,__name,__age):
        self.name=__name
        self.age=__age

        print("before added self")
        print("Student count: ".rjust(20),Student.count)
        print("self count: ".rjust(20),self.count)

        Student.count+=1
        #it should be same as th Student.count
        print("mid added")
        print("self count: ",self.count)
        self.count+=1

        print("after added self")
        print("Student count: ".rjust(20),Student.count)
        print("self count: ".rjust(20),self.count)
        print("\n\n")

s1=Student("Tomas",19)
s2=Student("Michael",20)

输出:

the first time to create an object of Student
before added self
     Student count:  0
        self count:  0
mid added
self count:  1
after added self
     Student count:  1
        self count:  2



before added self
     Student count:  1
        self count:  1
mid added
self count:  2
after added self
     Student count:  2
        self count:  3

分析:count=0 print(...)在初次进行实例化时调用,即s1创建的时候,self.count总是跟着student.count走,即若student.count更新,self.count的值即为新的student.count,单向影响。

Question:

  1. 实例化的过程具体为何,即count=0 print(...)语句只在第一次出现的原因
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值