__call__
控制类的调用过程,实际上在控制:对象的产生
class Mymeta(type):
def __call__(self,*args,**kwargs):
#print('xxx')
return 1
class Person(object,metaclass=Mymeta):
school = 'oldboy'
def __init__(self,name):
self.name =name
def score(self):
print('分数是100')
p =Person('nick')
print(p.name)
class Person():
school = 'oldboy'
def __init__(self,name):
self.name=name
def score(self):
print('分数是100')
def __call__(self,*args,**kwargs):
print('xxxxx')
p = Person('nick')#自动触发init的执行
#先触发元类的__call__
p()
#__new__
object
#给我把对象中的所有属性都设置成私有的
class Mymeta(type):
def __call__(self,*args,**kwargs):
#self 是Person这个类
#print(args)
#print(kwargs)
#return self(*args)#这里不行,会递归
#self.__new__(self)
#实例化产生一个Person类的对象,借助__new__来产生,需要吧类传过去,才能产生对象
#obj 是Person类的对象,只不过是空的
obj = object.__new__(self)
#obj =self.__nwe__(self)
#调用__init__方法完成初始化
#类来调用__init__方法,就是个普通函数,有几个参数就传几个参数
#self.__init__(obj,args,kwargs)
#对象来调用__init__方法,对象的绑定方法,会把自身传过来
obj.__init__(*args,**kwargs)
print(obj)
reutnr obj
class Person(object,metaclass=Mymeta):
school = 'oldboy'
def __init__(self,name):
self.name = name
def score(self):
print('分数是100')
p = Person(name = 'nick')
print(p)
print(p.name)
#把对象所有属性都变成私有
class Mymeta(type):
def __call__(self,*args,**kwargs):
obj = object.__new__(self)
obj.__init__(*args,**kwargs)
#print(obj.__dict__)
obj.__dict__={}