小编thr*_*ein的帖子

python - 类属性显然不是继承的

在最近的一个项目中,我尝试做这样的事情(更复杂,但结果相同):

class MetaA(type):
    def __new__(cls, name, args, kwargs):
        print kwargs["foo"]
        return type.__new__(cls, name, args, kwargs)

class A(object):
    __metaclass__ = MetaA
    foo = "bar"

class B(A):
    pass
Run Code Online (Sandbox Code Playgroud)

我明白了:

bar
Traceback (most recent call last):
  File "C:\Users\Thorstein\Desktop\test.py", line 10, in <module>
    class B(A):
  File "C:\Users\Thorstein\Desktop\test.py", line 3, in __new__
    print kwargs["foo"]
KeyError: 'foo'
Run Code Online (Sandbox Code Playgroud)

类属性是否未继承?如果是这样,在与上述类似的框架中是否有可能的解决方法?

编辑:可能更容易看到我的意思使用程序中的实际(简化)示例..

class GameObjectMeta(type):
    def __new__(cls, name, bases, attrs):
        attrs["dark_color"] = darken(*attrs["color"])
        return type.__new__(cls, name, bases, attrs)


class GameObject(object):
    __metaclass__ = GameObjectMeta
    color = (255,255,255)   # RGB tuple

class …
Run Code Online (Sandbox Code Playgroud)

python metaclass class-attributes

9
推荐指数
1
解决办法
2217
查看次数

标签 统计

class-attributes ×1

metaclass ×1

python ×1