Python中继承类中如何移除类属性?

8

考虑以下代码:

class A ():
   name = 7
   description = 8
   color = 9

class B(A):
   pass

现在,类B继承了类A的所有属性。但由于某种原因,我希望B不继承属性“color”。是否有可能做到这一点?
是的,我知道,我可以首先创建具有属性“name”和“description”的类B,然后从B继承添加属性“color”的类A。但在我的确切情况下,B实际上是A的简化版本,因此对我来说似乎更合理的是在B中删除属性(如果可能的话)。


3
如果B是A的简化版本,为什么不应该是A扩展B,而是反过来呢? - Johannes Charra
2个回答

9

我认为最好的解决方案是改变你的类层次结构,这样你就可以不用任何花哨的技巧获得你想要的类。

然而,如果你有一个非常好的理由不这样做,你可以使用描述符隐藏color属性。你需要使用新式类才能使其工作。

class A(object):
    name = 7
    description = 8
    color = 9

class Hider(object):
    def __get__(self,instance,owner):
        raise AttributeError, "Hidden attribute"

    def __set__(self, obj, val):
        raise AttributeError, "Hidden attribute"

class B(A):
    color = Hider()

当您尝试使用color属性时,将会出现AttributeError错误提示:
>>> B.color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance = B()
>>> instance.color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __get__
AttributeError: Hidden attribute
>>> instance.color = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __set__
AttributeError: Hidden attribute

@Graf - 在@Duncan的回答中首先提到了更改类层次结构 - 我只是提供了链接 - 所以我认为你应该真正接受他的答案。 - David Webb

8

您可以在B中为color提供不同的值,但如果您不希望B具有A的某些属性,则只有一种干净的方法:创建一个新的基类。

class Base():
    name = 7
    description = 8

class A(Base):
    color = 9

class B(Base):
    pass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接