Mateclass
一切皆对象:
Eg:
class Foo:
pass
f=Foo()
|
In [60]: print(type(f))
<class '__main__.Foo'>
In [61]: print(type(Foo))
<class 'type'>
|
即: f是Foo的对象 Foo是type的对象
那么我们现在不用type作为Foo的类:
-
# coding=utf-8
-
class Mytype(type):
-
def __init__(cls, what, bases=None, dict=None):
-
super().__init__(what, bases, dict)
-
print("Mytype_init_")
-
-
def __call__(self, *args, **kwargs):
-
return super().__call__(*args, **kwargs)
-
-
-
class Foo(metaclass=Mytype):
-
def __init__(self):
-
super().__init__()
-
print("Foo__init__")
-
-
@staticmethod
-
def __new__(cls, *more):
-
print("Foo__new__")
-
# return super().__new__(cls, *more)
解释器从上到下执行,9行之前,先由type创建Mytype类.到第11行,创建Foo对象,由type的__call__方法调用Mytype的__new__方法,再是__init__方法;
这时候执行,可以看到的运行结果为: Mytype_init_
|
下面继续:
-
# coding=utf-8
-
class Mytype(type):
-
def __init__(cls, what, bases=None, dict=None):
-
super().__init__(what, bases, dict)
-
print("Mytype_init_")
-
-
def __call__(self, *args, **kwargs):
-
print("Mytype____call__")
-
print(self.__name__) #Foo
-
print(self) #<class '__main__.Foo'>
-
# return super().__call__(*args, **kwargs)
-
-
-
-
class Foo(metaclass=Mytype):
-
def __init__(self):
-
super().__init__()
-
print("Foo__init__")
-
-
@staticmethod
-
def __new__(cls, *more):
-
print("Foo__new__")
-
# return super().__new__(cls, *more)
-
-
f=Foo()
可以看到在25行的时候后面加括号,调用了Foo对象的__call__方法,这时候self就是Foo,在这里调用self(Foo)的__new__方法,
|
接下来
-
# coding=utf-8
-
class Mytype(type):
-
def __init__(cls, what, bases=None, dict=None):
-
super().__init__(what, bases, dict)
-
print("Mytype_init_")
-
-
def __call__(self, *args, **kwargs):
-
print("Mytype____call__")
-
return super().__call__(*args, **kwargs)
-
-
-
-
class Foo(metaclass=Mytype):
-
def __init__(self):
-
super().__init__()
-
print("Foo__init__")
-
-
@staticmethod
-
def __new__(cls, *more):
-
print("Foo__new__")
-
print(super().__new__(cls, *more)) #<__main__.Foo object at 0x01F2BAD0>
-
return super().__new__(cls, *more)
-
-
f=Foo()
-
-
# Mytype_init_
-
# Mytype____call__
-
# Foo__new__
-
# <__main__.Foo object at 0x01F2BAD0>
-
# Foo__init__
-
#
-
# Process finished with exit code 0
So 当我们调用父类的方法时,顺带打印下我们关系的运行关系:
可以看到,object对象是在__new__方法中生成的.
|
总结:实例化一个类: 先在定义类的时候,解释器已经对其进行解释,type类执行,实例化的时候type类的__call__方法被调用,type.__call__方法将调用该类的__new__方法.此时对象生成,然后该类的__init__方法被调用.
即:实例化一个类,他的__new__方法先被执行,并在此时创建对象,然后,__init__方法被执行