要點:
1.內置函數__str()__被重寫。
def __str__(self): return Animal.species+" is "+self.name
2.系統sys.getrefcount(cat))獲得實例cat的引用次數
3.判斷是否被實例化
for obj in gc.get_objects():#判斷是否有類被實例化 if isinstance(obj,Animal): print("被實例化的是%s"%obj.name)
4.要調用模塊sys和gc(垃圾收集)
下面是代碼:
import sys
import gc
class Animal():
"This is Animal species class."
species="Animal"#類的靜態變量,所有對象共享。
count=0
def __init__(self,name):
self.name=name#z在init定義的是對象變量。
self.attri=[]#並以“self."打頭爲對象變量,所有對象共享。
Animal.count+=1#統計類的實例個數
def __del__(self):
print("解構函數del被調用")
def __str__(self):
return Animal.species+" is "+self.name
def add_attributes(self,attri):#爲attri賦值的方法
if(type(attri)==list):
self.attri.extend(attri)
else:
self.attri.append(attri)
cat=Animal("Tom")
miaomiao=cat
xiaohua=cat
print(str(cat))
print("引用的個數是:%s"%sys.getrefcount(cat))
print("刪除一個引用。")
輸出是: