要点:
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("删除一个引用。")
输出是: