由于公开的属性是类属性,因此在创建类时构造所需的列表(类的公开属性及其祖先的属性)是有意义的,您可以使用元类。(编辑:我看到评论中提出了同样的建议。)
这是一个这样做的例子:
class ExposedMeta(type):
def __init__(cls, name, bases, attrs):
if not "exposed_properties" in attrs:
cls.exposed_properties = []
all_props = set(cls.exposed_properties)
for base in bases:
all_props.update(getattr(base, "all_exposed_properties", []))
cls.all_exposed_properties = list(all_props)
super(ExposedMeta, cls).__init__(name, bases, attrs)
class A(object):
__metaclass__ = ExposedMeta
exposed_properties = ['A1', 'A2']
class B(A):
exposed_properties = ['B']
class C(A):
pass
class D(object):
__metaclass__ = ExposedMeta
exposed_properties = ['D']
class E(B, D):
exposed_properties = ['E1', 'E2']
for cls in [A, B, C, D, E]:
print "Class %s, exposed: %s, all exposed: %s" % (cls.__name__, cls.exposed_properties, cls.all_exposed_properties)