简体   繁体   English

删除继承类Python中的class属性

[英]Remove class attribute in inherited class Python

Consider such code: 考虑这样的代码:

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

class B(A):
   pass

Class B now has (inherits) all attributes of class A. For some reason I want B not to inherit attribute 'color'. B类现在具有(继承)A类的所有属性。出于某种原因,我希望B不继承属性'color'。 Is there a possibility to do this? 有可能这样做吗?
Yes, I know, that I can first create class B with attributes 'name' and 'description' and then inherit class A from B adding attribute 'color'. 是的,我知道,我可以先创建具有属性'name'和'description'的B类,然后从B继承A类添加属性'color'。 But in my exact case, B is actually a reduced version of A, so for me it seems more logical to remove attribute in B (if possible). 但在我的确切情况下,B实际上是A的简化版本,所以对我来说,删除B中的属性似乎更合乎逻辑(如果可能的话)。

I think the best solution would be to change your class hierarchy so you can get the classes you want without any fancy tricks. 我认为最好的解决方案是改变你的类层次结构,这样你就可以得到你想要的类,而不需要任何花哨的技巧。

However, if you have a really good reason not to do this you could hide the color attribute using a Descriptor. 但是,如果你有充分的理由不这样做,你可以使用描述符隐藏color属性 You'll need to be using new style classes for this to work. 您需要使用新的样式类来实现此功能。

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

You'll then get an AttributeError when you try to use the color attribute: 当您尝试使用color AttributeError时,您将获得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

You can supply a different value for color in B, but if you want B not to have some property of A then there's only one clean way to do it: create a new base class. 您可以在B中为color提供不同的值,但是如果您希望B不具有A的某些属性,那么只有一种干净的方法:创建一个新的基类。

class Base():
    name = 7
    description = 8

class A(Base):
    color = 9

class B(Base):
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM