问题回顾:
定义一个类属性,记录通过这个类创建了多少对象?
代码献上:
class Person(object):
# __count = 0 #类属性
count = 0
def __new__(cls, *args, **kwargs):
x = object.__new__(cls) #申请内存,创建一个对象,并设置类型:Person类
return x
def __init__(self, name, age):
Person.count += 1
self.name = name
self.age = age
# @classmethod
# def get__count(cls):
# return cls.__count
# 每次创建对象,都会调用__new__和__init__方法
p1 = Person('zhanan', 12)
p2 = Person('liss', 20)
p3 = Person('ytsc', 18)
print(Person.count)
运行结果:
3