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

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 = a


test0 = test('c')
test1 = test('b')
# test3 = test('a')

print(test1.count)
del test1
del test0
print(test1.count)

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

posted @ 2018-04-29 21:06  盈波秋水泛清涛  阅读(1173)  评论(0编辑  收藏  举报