Python-19-元类

一、定义

元类就是类的类

type是python的一个内建元类

类的两种定义方式

# 定义类的两种方式
class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

print(Foo)  # <class '__main__.Foo'>


def __init__(self, name, age):
    self.name = name
    self.age = age
def test():
    print('====')

FFo = type('Foo', (object,), {'x': 1, '__init__': __init__, 'test': test})
print(FFo)  # <class '__main__.Foo'>
f1 = FFo('alex', 18)
print(f1.__dict__)  # {'name': 'alex', 'age': 18}

二、自定义元类

如果一个类没有声明自己的元类,默认他的元类是type,除了使用元类type,用户也可以自定义元类

class MyType(type):
    def __init__(self, a, b, c):
        print('元类的构造函数开始运行')

    def __call__(self, *args, **kwargs):
        obj = object.__new__(self)
        self.__init__(obj, *args, **kwargs)
        return obj


class Foo(metaclass=MyType):  # Foo = MyType(Foo, 'Foo', (), {})
    def __init__(self, name):
        self.name = name


f1 = Foo('alex')

猜你喜欢

转载自www.cnblogs.com/lsf123456/p/11206737.html