删除继承类Python中的class属性

时间:2010-09-09 07:32:29

标签: python inheritance class-attributes

考虑这样的代码:

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

class B(A):
   pass

B类现在拥有(继承)A类的所有属性。出于某种原因,我希望B不要继承属性'color'。是否有可能这样做?
是的,我知道,我可以先创建具有属性'name'和'description'的B类,然后从B继承A类添加属性'color'。但在我的确切情况下,B实际上是A的减少版本,所以对我而言,删除B中的属性似乎更合乎逻辑(如果可能)。

2 个答案:

答案 0 :(得分:8)

我认为最好的解决方案是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()

当您尝试使用AttributeError属性时,您将获得color

>>> 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

答案 1 :(得分:7)

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

class Base():
    name = 7
    description = 8

class A(Base):
    color = 9

class B(Base):
    pass