2010-09-09 117 views
5

考虑这样的代码:删除类属性

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

class B(A): 
    pass 

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

+3

如果B是A的一个简化版本,为什么不上延伸,而不是其他的方式B,回合? – 2010-09-09 07:38:59

回答

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

你说得对,我应该改变我的班级结构。 – Graf 2010-09-15 12:48:56

+0

@格拉夫 - 改变类层次结构首先在@邓肯的答案中 - 我只是将它链接起来 - 所以我认为你应该真的接受他的答案。 – 2010-09-15 12:55:38

7

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

class Base(): 
    name = 7 
    description = 8 

class A(Base): 
    color = 9 

class B(Base): 
    pass