metaclass

# 1、类创建的两种方式
class Foo(object):
    a1 = 123

    def func(self):
        return 666

# Foo = type("Foo", (object,), {"a1": 123, "func": lambda x: x + 1})

# 2、自定义type
# class MyType(type):
#     pass
#
#
# Foo = MyType("Foo", (object,), {"a1": 123, "func": lambda x: x + 1})
# 注意:metaclass作用是指定由谁来创建当前类

 

 

class MyType(type):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def __call__(cls, *args, **kwargs):
        obj = cls.__new__(*args, **kwargs)
        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


# Foo是类
# Foo是MyType的一个对象
obj = Foo()

 

 

创建类时,先执行type的__init__方法。
当类实例化时,先执行type的call方法,返回值是当前类的实例化对象

 

posted @ 2018-09-27 10:37  慕沁  阅读(121)  评论(0)    收藏  举报