首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >污染班级环境

污染班级环境
EN

Stack Overflow用户
提问于 2010-01-06 19:52:19
回答 5查看 144关注 0票数 1

我有一个对象,它保存了大量静态访问的I。我想把它拆分成另一个对象,这个对象只保存那些I,而不需要修改已经存在的代码库。举个例子:

代码语言:javascript
复制
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__,所以我正在尝试找到一种方法来实现这一点(也许是元类?)

EN

回答 5

Stack Overflow用户

发布于 2010-01-06 20:15:54

尽管这不是创建子类化的确切目的,但它实现了您所描述的:

代码语言:javascript
复制
class _CarType(object):
    DIESEL_CAR_ENGINE = 0
    GAS_CAR_ENGINE = 1 # lots of these ids

class Car(_CarType):
    types = _CarType
票数 4
EN

Stack Overflow用户

发布于 2010-01-06 19:57:55

类似于:

代码语言:javascript
复制
class Car(object):
    for attr, value in _CarType.__dict__.items():
        it not attr.startswith('_'):
            locals()[attr] = value
    del attr, value

或者您可以在类声明之外执行此操作:

代码语言:javascript
复制
class Car(object):
    # snip

for attr, value in _CarType.__dict__.items():
    it not attr.startswith('_'):
        setattr(Car, attr, value)
del attr, value
票数 3
EN

Stack Overflow用户

发布于 2010-01-06 20:27:41

这就是如何使用元类来实现这一点:

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2012698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档