python: 2.7
元类的一个重要作用是用于类验证.。如果一个类必须遵循特定的接口,元类将是强制使其符合规范的有效方式。
例如:一个类需要设置两个属性中的一个,但是不需要两个属性都设置。使用元类的方式,代码如下:
class FooOrBar(type):
def __new__(cls, name, bases, attrs):
if 'foo' in attrs and 'bar' in attrs:
raise TypeError('Class {} cannot contain both `foo` and `bar`.'.format(name))
if 'foo' not in attrs and 'bar' not in attrs:
raise TypeError('Class {} must contain either `foo` or `bar`.'.format(name))
return super(FooOrBar, cls).__new__(cls, name, bases, attrs)
class A(object):
__metaclass__ = FooOrBar
foo =1
class AA(A):
bar = 2
但是上面的代码有一个很严重的问题,那就是子类并不会继承该功能。例如:子类AA实例foo
、bar
属性同时存在。
原因:元类直接检查attrs属性,但这只是包含所声明类的属性集,它并不知道任何继承自基类的属性集。
更好的方法
class FooOrBar(type):
def __new__(cls, name, bases, attrs):
answer = super(FooOrBar, cls).__new__(cls, name, bases, attrs)
if hasattr(answer, 'foo') and hasattr(answer, 'bar'):
raise TypeError('Class {} cannot contain both `foo` and `bar`.'.format(name))
if not hasattr(answer, 'foo') and not hasattr(answer, 'bar'):
raise TypeError('Class {} must contain either `foo` or `bar`.'.format(name))
return answer
class A(object):
__metaclass__ = FooOrBar
foo =1
class AA(A):
bar = 2
两种方法的区别:后者在__new__
第一行调用type
的构造函数从基类获取所有属性,并在实例化类返回之前检查它的属性,而不是查看attrs字典。