我不知道它是否可以通过任何其他方式轻松完成,但我自己使用元类提出了一个解决方案。
解决方案:
class MetaBase(type):
def __init__(cls, name, bases, namespace):
super(MetaBase, cls).__init__(name, bases, namespace)
if '_superclass' in namespace: # A special attribute to distinguish between superclasses and subclasses
if '_attrnames' not in namespace:
raise AttributeError('"_attrnames" needs to be defined as a class attribute in a superclass.')
else:
if 'classvars' in namespace: # Allow for define all required class attributes in one iterable attribute
for attrname, attr in zip(getattr(cls.__mro__[1], '_attrnames'), getattr(cls, 'classvars')): # Get all the varnames in the superclass's "varnames", as well as the values
setattr(cls, attrname, attr)
namespace[attrname] = attr
delattr(cls, 'classvars')
else:
for attrname in getattr(cls.mro()[1], '_attrnames'):
if attrname not in namespace:
raise AttributeError('"%s" not defined, but is required.' % attrname)
class Base(metaclass=MetaBase):
_superclass = True # The value of this attribute doesn't matter
_attrnames = ('a','b','c')
class Sub1(Base):
a = 1
b = 2
c = 3
class Sub2(Base):
classvars = (1, 2, 3)