本文實例分析了Python類屬性與實例屬性用法。分享給大家供大家參考。具體如下:
類屬性:類名.屬性名
實例屬性:實例.屬性名
>>> class test():... ver=1... >>> a=test()>>> test.x=8>>> a.__dict__{}>>> a.x8>>> a.x=9>>> a.__dict__{'x': 9}
1.類的屬性如何模子一樣,類屬性一旦給出,所有的實例將都取這個值。
2.各個實例的這個屬性的值可以變化。
3.某一實例的屬性沒有顯示地給定,a.x可以顯示這個屬性的值,但是,它沒有在名稱空間里面。
為了把它加入名稱空間,必須顯式賦值。
class Instant1(object): count=0 def __init__(self): Instant1.count=Instant1.count+1 print "created instant" def howmany(self): print Instant1.count print self.countclass Instant2(object): count=0 def __init__(self): print self.count #print Instant2.count self.count=self.count+1 #Instant2.count=Instant2.count+1 print "created instant" def howmany(self): print self.count print Instant2.count
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答