我有一个对象,它保存了大量静态访问的I。我想把它拆分成另一个对象,这个对象只保存那些I,而不需要修改已经存在的代码库。举个例子:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car(object):
types = _CarType我希望能够通过调用Car.types.DIESEL_CAR_ENGINE来访问_CarType.DIESEL_CAR_ENGINE,或者通过Car.DIESEL_CAR_ENGINE来实现与现有代码的向后兼容。很明显,我不能使用__getattr__,所以我正在尝试找到一种方法来实现这一点(也许是元类?)
发布于 2010-01-06 20:15:54
尽管这不是创建子类化的确切目的,但它实现了您所描述的:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car(_CarType):
types = _CarType发布于 2010-01-06 19:57:55
类似于:
class Car(object):
for attr, value in _CarType.__dict__.items():
it not attr.startswith('_'):
locals()[attr] = value
del attr, value或者您可以在类声明之外执行此操作:
class Car(object):
# snip
for attr, value in _CarType.__dict__.items():
it not attr.startswith('_'):
setattr(Car, attr, value)
del attr, value发布于 2010-01-06 20:27:41
这就是如何使用元类来实现这一点:
class _CarType(type):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
def __init__(self,name,bases,dct):
for key in dir(_CarType):
if key.isupper():
setattr(self,key,getattr(_CarType,key))
class Car(object):
__metaclass__=_CarType
print(Car.DIESEL_CAR_ENGINE)
print(Car.GAS_CAR_ENGINE)https://stackoverflow.com/questions/2012698
复制相似问题