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(...)语句只在第一次出现的原因

你可能感兴趣的:(Python)