在python2中可以通过定义一个类级别属性__metaclass__来实创建元类,不过在python3中取消了__metaclass__属性。python3中可以通过在定义类的时候声明metaclass参数来创建元类。
实例1:增加一个__author__类属性
class Author(type): def __new__(cls, name, bases, attrs): attrs['__author__'] = 'xiemanR' return type.__new__(cls, name, bases, attrs) class MyBlog(metaclass=Author): pass print(MyBlog.__author__) a = MyBlog() print(a.__author__)
实例2:使用元类创建单例模式
class Singleton(type): def __new__(cls, name, bases, attrs): print('new') attrs['instance'] = None return super(Singleton, cls).__new__(cls, name, bases, attrs) def __call__(cls, *args, **kwargs): print('call') if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance class Foo(metaclass=Singleton): pass x = Foo() y = Foo() print(id(x)) print(id(y))
实例3:将类属性转化为大写的形式
class Upper(type): def __new__(cls, name, bases, dct): attrs = ((name, value) for name, value in dct.items() if not name.startswith('__')) uppercase_attr = dict((name.upper(), value) for name, value in attrs) return type.__new__(cls, name, bases, uppercase_attr) class Bar(metaclass=Upper): foo = 'foo' test = 'test' b = Bar() print(b.FOO) print(b.TEST)