Python 类的祖宗--metaclass

1.Python 中一切事物都是对象
2.类都是 type 类的对象

类的两种申明方法

# 方法一:
class Foo:
    def func(self):
        print(666)

obj = Foo()
obj.func()

# 方法二:
def function(self):
    print(777)

Foo = type('Foo', (object,), {'func': function})
#type第一个参数:类名
#type第二个参数:当前类的基类
#type第三个参数:类的成员

obj = Foo()
obj.func()

运行结果:
666
777
class MyType(type):
    def __init__(self, *args, **kwargs):
        print(666)

    def __call__(self, *args, **kwargs):
        print(777)


class Foo(object,metaclass=MyType):
    def func(self):
        print('hello klvchen')

obj = Foo()

运行结果:
666
777
class MyType(type):
    def __init__(self, *args, **kwargs):
        print(666)

    def __call__(self, *args, **kwargs):
        r = self.__new__(self)


class Foo(object,metaclass=MyType):
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        return '对象'

    def func(self):
        print('hello klvchen')

obj = Foo()

运行结果:
666

创建对象时,调用__init__()方法的过程

参考 https://www.cnblogs.com/wupeiqi/p/4766801.html

猜你喜欢

转载自www.cnblogs.com/klvchen/p/9194037.html