Person.count+=1為什么不能寫成self.count+=1 ?
class?Person(): ????count=0 ????def?__init__(self,name): ????????self.name=name ????????Person.count+=1?????#為什么這里不可以用self.count+=1? p1=Person('xiaoming') p2=Person('hanmeimei') p3=Person('xiaoli') print(p3.count)
2020-03-12
明白了,謝謝!
2020-03-12
因為self表示引用這個方法的實例,而這個count是類的屬性,如果你用實例來修改,只會另外為它自己創建一個count屬性。而不會修改類的屬性。實例屬性是獨立的。