Inheriting from classes unpacked from a list
假设我在python(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class A(object): pass class B(object): pass class C(object): pass classes = [A, B, C] class D(*classes): pass |
不幸的是,当我执行此操作时,会出现语法错误。除了写
可以使用
1 2 3 4 5 6 | >>> classes = [A, B, C] >>> D = type('D', tuple(classes), {}) >>> type(D) <class 'type'> >>> D.__bases__ (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>) |
更多示例请参见15247075。
一种方法是创建一个decorator,然后使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | def modify_bases(bases): def decorator(cls): return type(cls.__name__, tuple(classes), dict(cls.__dict__)) return decorator ... >>> %cpaste @modify_bases(classes) class D: x = 1 y = 2 >>> D.mro() [<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <type 'object'>] |