使用metaclass验证子类

实验代码

# coding: utf-8

# Python2中定义Metaclass, 该Metaclass要继承自type, 实现__new__方法
class MetaCls(type):
    def __new__(meta, name, bases, class_dict):
        print (meta, name, bases, class_dict)
        if class_dict['val'] < 0:
            raise ValueError('ERROR: val[%s] < 0!!!' % class_dict['val'])
        return type.__new__(meta, name, bases, class_dict)


# 使用者要通过__metaclass__变量指定要使用的Metaclass
# Metaclass中所编写的验证逻辑, 针对的是该基类的子类, 而非基类本身
class BaseCls(object):
    __metaclass__ = MetaCls
    val = None


# 验证成功
class Derived1Cls(BaseCls):
    val = 1


# 验证失败
class Derived2Cls(BaseCls):
    val = -2

执行

python main.py

运行结果

# ('__main__.MetaCls'>, 'BaseCls', ('object'>,), {'__module__': '__main__', '__metaclass__': '__main__.MetaCls'>, 'val': None})
# Traceback (most recent call last):
#   File "main.py", line 11, in 
#     class BaseCls(object):
#   File "main.py", line 7, in __new__
#     raise ValueError('ERROR: val[%s] < 0!!!' % class_dict['val'])
# ValueError: ERROR: val[None] < 0!!!

参考

《Effective Python》第33条, 用元类来验证子类

你可能感兴趣的:(Python)