__init__方法
? __init__方法在類的一個對象被建立奢赂,馬上運(yùn)行排霉。用來對你的對象初始化偏竟。
? 注意煮落,這個名稱的開始和結(jié)尾都是雙下劃線。(__init__方法類似于c++,c#和Java中的constructor)
例
class Peeson(self,name):
? ? def __init__(self,name):
? ? ? ? ? self.test_name = name
? ? def say(self):
? ? ? ? ? print("Hello,name is {}".format(self.name))
? ? ? ? self.test = "1234"
? ? ? ? # 屬性可以隨處定義踊谋,不需要先定義
? ? ? ? print("the test is "+self.test)
P = Person("xiaoming")
# 打印xiaoming,1234
P.say()
print("the Person test is "+p.test)
p.test2 = "haha..."
print("the Person test2 is "+p.test2)
# 打印haha....
名稱? ? ? 說明
__init__(self) 這個方法在新建對象恰好要被返回使用之前被調(diào)用
__del__(self) 在對象要被刪除之前調(diào)用蝉仇。如使用del刪除
__str__(self) 在我們對對象使用print語句或是使用str()的時候調(diào)用
__lt__(self,other) 當(dāng)使用小于 運(yùn)算符(<)的時候調(diào)用
__gt__(self,other) 當(dāng)使用大于 運(yùn)算符(>)的時候調(diào)用
__eq__(self,other) 當(dāng)使用等于 運(yùn)算符(==)的時候調(diào)用
__ne__(self,other) 當(dāng)使用不等于 運(yùn)算符(!=)的時候調(diào)用
__le__(self,other) 當(dāng)使用小于等于 運(yùn)算符(<=)的時候調(diào)用
__ge__(self,other) 當(dāng)使用大于等于 運(yùn)算符(>=)的時候調(diào)用
__add__(self,other) 當(dāng)使用加 運(yùn)算符(+)的時候調(diào)用
__getitem__(self,key) 當(dāng)使用x[key] 索引操作符的時候調(diào)用
__len__(self) 對序列對象使用內(nèi)建的len()函數(shù)的時候調(diào)用