Python之面向对象元类
Python之面向对象元类
call方法:
1 class People: 2 def __init__(self,name): 3 self.name=name 4 # 5 def __call__(self, *args, **kwargs): 6 print('call') 7 # 8 9 p=People('George') 10 print(callable(People)) 11 print(callable(p)) 12 13 p()
元类:
1 class People: 2 def __init__(self,name): 3 self.name=name 4 5 6 p=People('egon') 7 8 9 # print(type(p)) 10 # 11 # print(type(People)) 12 13 #typer--->类------>对象 14 15 16 class Foo: 17 x=1 18 def run(self): 19 pass 20 print(type(Foo)) 21 22 23 #type成为元类,是所有类的类,利用type模拟class关键字的创建类的过程 24 def run(self): 25 print('%s is runing' %self.name) 26 27 class_name='Bar' 28 bases=(object,) 29 class_dic={ 30 'x':1, 31 'run':run 32 } 33 34 Bar=type(class_name,bases,class_dic) 35 print(Bar) 36 print(type(Bar))
自定义元类:
1 # class Foo(metaclass=type): 2 # x=1 3 # def run(self): 4 # print('running') 5 # 6 # 7 # # type('Foo',(object,),{'x':1,'run':run}) 8 9 10 11 # class Mymeta(type): 12 # def __init__(self,class_name,class_bases,class_dic): 13 # # print(self) 14 # # print(class_name) 15 # # print(class_bases) 16 # # print(class_dic) 17 # for key in class_dic: 18 # if not callable(class_dic[key]):continue 19 # if not class_dic[key].__doc__: 20 # raise TypeError('小子,你没写注释,赶紧去写') 21 # 22 # # type.__init__(self,class_name,class_bases,class_dic) 23 # class Foo(metaclass=Mymeta): 24 # x=1 25 # def run(self): 26 # 'run function' 27 # print('running') 28 29 # Foo=Mymeta('Foo',(object,),{'x':1,'run':run}) 30 31 # print(Foo.__dict__) 32 33 34 35 class Mymeta(type): 36 def __init__(self,class_name,class_bases,class_dic): 37 pass 38 def __call__(self, *args, **kwargs): 39 # print(self) 40 obj=self.__new__(self) 41 self.__init__(obj,*args,**kwargs) #obj.name='egon' 42 return obj 43 class Foo(metaclass=Mymeta): 44 x=1 45 def __init__(self,name): 46 self.name=name #obj.name='egon' 47 def run(self): 48 'run function' 49 print('running') 50 # print(Foo.__dict__) 51 52 f=Foo('egon') 53 54 print(f) 55 56 print(f.name)