构造类的方法
方法一: class
1 class Foo():
2 pass
方法二: type 构造类
def __init__(self,a): self.a = a def func1(self,b): print(self.a,"<<<<func1") print(b,"<<<<func1") Foo = type('Foo',(object,),{ '__init__': __init__, # __init__ 固定名 'func1':func1, }) obj = Foo('liumeng') print(obj) print(obj.a,"<<<< obj.a") obj.func1('lalala')
方法三: metaclass 构造类
1 class Mytype(type): 2 def __call__(self, *args, **kwargs): 3 obj = self.__new__(self, *args, **kwargs) # 创建一个空对象 4 obj.__init__(*args, **kwargs) # 对象的构造 5 return obj # 返回对象 6 class Foo(metaclass=Mytype): 7 def __init__(self,a,b): 8 self.a = a 9 self.b = b 10 def __call__(self, *args, **kwargs): 11 print('lalala') 12 obj = Foo('alex','egon') # 调用 call()方法 不会调用自己的 因为Foo类是通过Mytype类构造出来的,即Foo是Mytype类的对象,Foo()调用Mytype类的call方法 13 print(Foo) # <class '__main__.Foo'> 14 print(obj) # <__main__.Foo object at 0x000000000294CF98> 15 print(obj.a) 16 print(obj.b) 17 print(obj())