python对象的创建和实例的生成次数,python对象,pyhton用__n


pyhton用__new__来创建对象(__new__相当于Java中的构建函数),

对象创建好之后会立即调用__init__方法来初始化对象,__init__方法有个参数self就是刚才__new__创建好的那个对象。通过我们有__init__方法中给对象的属性进行赋值,或者动态线对象添加属性并赋值

class test(object):    count = 0    def __new__(cls, *args, **kwargs):        test.count += 1        if test.count >2:           raise Exception("大于2次实例化")        return super(test, cls).__new__(cls)    def __init__(self,a):        self.a = atest0 = test(‘c‘)test1 = test(‘b‘)# test3 = test(‘a‘)print(test1.count)del test1
del test0
print(test1.count)

当使用del objectname时则销毁这个对象的实例,当这个对象的引用计数为0的时候,就会被回收

python对象的创建和实例的生成次数

评论关闭