#只是储备 __call__方法:# class Foo:# def __call__(self, *args, **kwargs):# print(self)# print(args)# print(kwargs)# obj = Foo()# obj(1, 2, 3, a = 5, g = 8)‘‘‘在python中一切都是对象, 此地,Foo也是对象,Foo可以加括号调用,所以 obj也可以加括号调用但是obj这个对象的类的内部必须有__call__方法,此地可以引出, Foo的元类内部也有__call__方法‘‘‘#Foo(1,2,3,a = 5, g = 8)就等于 Foo.__call__(Foo, 1,2,3,a = 5, g = 8) 激活type的__call__方法 class Mymeta(type): def __init__(self, class_name, class_bases, class_dic): # if not class_name.istitle(): # raise TypeError(‘首字母必须大写‘) # if ‘__doc__‘ not in class_dic or not class_dic[‘__doc__‘].strip(): # raise TypeError(‘必须写注释且不能为空!‘) # print(class_name) # print(class_bases) # print(class_dic) super(Mymeta, self).__init__(class_name, class_bases, class_dic) #print(self) def __call__(self, *args, **kwargs): #obj = Chinese(‘egon‘, age = 25) # print(self) #Chinese = self # print(args) #args = ‘egon‘ # print(kwargs) #kwargs = 18 #第一件事:造一个空对象 obj obj = object.__new__(self) #第二件事:初始化 就是 __init__ self.__init__(obj, *args, **kwargs) #第三件事:返回 对象 obj return obj class Chinese(object, metaclass=Mymeta): country = ‘china‘ def __init__(self, name, age): self.name = name self.age = age def talk(self): print(‘老王的媳妇出轨啦!‘)obj = Chinese(‘egon‘, 25) #相当于 Chinese.__call__(chinese, ‘egon‘, 25)‘‘‘Chinese(‘egon‘, 25) 等同于 Chinese.__call__(‘egon‘, 25) 触发__call__方法,然后创建一个空对象,然后实例化就是 __init__,最后把对象返回给调用者,就是自己定义的那个类的对象‘‘‘ #print(obj.__dict__)
原文地址:https://www.cnblogs.com/yuexijun/p/10324938.html
时间: 2024-11-08 03:47:04