1、python中一切事物都是对象
2、类都是type类的对象,type(……),“对象”都是以类的对象,类()
class Foo:
def func(self):
print('123')
obj = Foo()
############################
# type('Foo', (object,), {'func': lambda x:123}) 声明了一个类,类中有一个成员func
Foo = type('Foo', (object,), {'func': lambda x:123})
obj = Foo()
# 上面两个都是声明了一个类
# obj是对象,Foo类的对象
# Foo类也是一个对象,是type的对象
class MyType(type):
def __init__(self, *args, **kwargs):
print(123)
pass
class Foo(object, metaclass=MyType):
def func(self):
print("hello world!")
# 没有任何调用的时候就可以打印123
class MyType(type):
def __init__(self, *args, **kwargs):
# self = Foo类
print(123)
pass
# 这里的self是MyType的对象,也就是Foo类
def __call__(self, *args, **kwargs):
# self = Foo类
obj = self.__new__()
self.__init__(obj)
class Foo(object, metaclass=MyType):
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
return object.__new__(cls, *args, **kwargs)
def func(self):
print("hello world!")
# 没有任何调用的时候就可以打印123
obj = Foo() # Foo是MyType的对象,对象()执行__call__方法
# 打印123 456,先执行MyType里的__init__方法,再执行__call__方法
# 第一阶段,执行MyType中的__init__方法
# 第二阶段,执行obj = Foo()时,先执行MyType里的__call__方法,再执行Foo类中的__new__方法
# 在__new__中object调用__new__方法创建一个Foo对象