1 classDog (object):2N=1233Name='class variable name'4n_list=[]5 6 def __init__(self,name,life_value=100):#Pass Parameters7Self.name=name8Self.__life_value=Life_value9 Ten def __del__(self): One Print("%s Dead"%self.name) A - defShow_status (self): - Print("Test Private variable call name:%s,life_value:%s"% (self.name,self.__life_value)) the - defBulk (self): - Print("%s is Wang Wang Wang"%self.name) - +D1=dog ("Huanhuan") - D1.bulk () + Print("D1:", D1.NAME,D1.N) AD1.n_list.append ('D1,') atD1.wierd=true#Increase - Print("D1:", D1.name,d1.n,d1.n_list,d1.wierd) - d1.show_status () - delD1.n#Delete - - delD1 in -D2=dog ('Lele') toD2.n_list.append ('D2,') + Print("D2:", D2.name,d2.n,d2.n_list) - the Print("Dog:", dog.name,dog.n,dog.n_list)
constructor: Do some initialization work in the instantiation process, pass the parameter.
def __init__ (self,name,life_value=100): #传参数 7 self.name=name 8 self.__life_value=life_ Value
Call: D1=dog (' Huanhuan ')
Expand to see:
D1.name= ' Huanhuan '
d1.__life_value=100
destructor: When the instance is released or revoked, do the finishing touches, such as disconnecting the database, closing the open temporary file
def __del__(self): print ("%s dead"% self.name)
D1 del #删除d1实例,(sectarianism No, house can be torn down), destroying objects, performing destructors
And the program does not write Del D2, so the D2 object destructor is called at the end of the entire program .
private property, private method: external cannot be called directly and must be called through other methods of the class.
8 self.__life_value=life_value (previous __)
Call:
def show_status (self): print ("Test private variable Call name:%s,life_value:%s"% (Self.name,)
cannot be directly on external print (self.__life_value) error
#私有方法
def __sleep (self): Print (' Private method:%s is sleeping' %self.name) #调用私有方法 def Show_status (self): self . __sleep ()
Python Object-oriented