繁体   English   中英

删除继承类Python中的class属性

[英]Remove class attribute in inherited class Python

考虑这样的代码:

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中的属性似乎更合乎逻辑(如果可能的话)。

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

但是,如果你有充分的理由不这样做,你可以使用描述符隐藏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时,您将获得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

您可以在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