【问题标题】:Remove class attribute in inherited class Python删除继承类 Python 中的类属性
【发布时间】:2011-04-10 03:07:33
【问题描述】:

考虑这样的代码:

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

class B(A):
   pass

B 类现在具有(继承)A 类的所有属性。出于某种原因,我希望 B 不继承属性“颜色”。有没有可能做到这一点?
是的,我知道,我可以首先创建具有属性“名称”和“描述”的 B 类,然后从 B 添加属性“颜色”继承 A 类。但在我的确切情况下,B 实际上是 A 的 reduced 版本,所以对我来说,删除 B 中的属性(如果可能的话)似乎更合乎逻辑。

【问题讨论】:

  • 如果 B 是 A 的简化版,为什么 A 不扩展 B 而不是反过来呢?

标签: python inheritance class-attributes


【解决方案1】:

我认为最好的解决方案是change your class hierarchy,这样您就可以获得所需的课程,而无需任何花哨的技巧。

但是,如果您有充分的理由不这样做,您可以隐藏 color 属性 using a Descriptor. 您需要使用新的样式类才能使其工作。

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 的回答中 - 我刚刚链接到它 - 所以我认为你应该真的接受他的回答。
【解决方案2】:

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

class Base():
    name = 7
    description = 8

class A(Base):
    color = 9

class B(Base):
    pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2011-01-30
    • 2016-11-11
    相关资源
    最近更新 更多