本文實(shí)例分析了Python類屬性與實(shí)例屬性用法。分享給大家供大家參考。具體如下:
類屬性:類名.屬性名
實(shí)例屬性:實(shí)例.屬性名
>>> class test():... ver=1... >>> a=test()>>> test.x=8>>> a.__dict__{}>>> a.x8>>> a.x=9>>> a.__dict__{'x': 9}1.類的屬性如何模子一樣,類屬性一旦給出,所有的實(shí)例將都取這個(gè)值。
2.各個(gè)實(shí)例的這個(gè)屬性的值可以變化。
3.某一實(shí)例的屬性沒有顯示地給定,a.x可以顯示這個(gè)屬性的值,但是,它沒有在名稱空間里面。
為了把它加入名稱空間,必須顯式賦值。
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
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
|
新聞熱點(diǎn)
疑難解答
圖片精選