-对象为什么可以被for循环?
答:变为可迭代对象。
class Foo(object): # def __iter__(self): # return iter([11,22,33]) def __iter__(self): yield 1 yield 2 yield 3 obj = Foo() for item in obj: print(item) ''' 1 2 3 '''
new方法的返回值决定对象到底是什么
class Bar(object): pass class Foo(object): def __new__(cls, *args, **kwargs): # return super(Foo,cls).__new__(cls,*args, **kwargs) return Bar() obj = Foo() print(obj) #<__main__.Bar object at 0x03450910> # class Bar(object): # def __init__(self,cls): # self.cls = cls # # class Foo(object): # # def __new__(cls, *args, **kwargs): # return super(Foo,cls).__new__(cls,*args, **kwargs) # # obj = Foo() # print(obj) #<__main__.Foo object at 0x02F30090>
- metaclass:指定当前类由谁来创建
如果一类自己或基类中指定了metaclass,那么该类就是由metaclass指定的type或mytype创建。
- 创建类时,先执行type的__init__。
- 类的实例化时,执行type的__call__,__call__方法的的返回值就是实例化的对象。
__call__内部调用:
- 类.__new__,创建对象
- 类.__init__,对象的初始化
class MyType(type): def __init__(self,*args,**kwargs): super(MyType,self).__init__(*args,**kwargs) def __call__(cls, *args, **kwargs): obj = cls.__new__(cls) cls.__init__(obj,*args, **kwargs) return obj class Foo(object,metaclass=MyType): a1 = 123 def __init__(self): pass def __new__(cls, *args, **kwargs): return object.__new__(cls) def func(self): return 666 obj = Foo()