删除继承类Python中的类属性

问题描述 投票:0回答:3

考虑这样的代码:

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

class B(A):
   pass

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

python inheritance class-attributes
3个回答
9
投票

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

但是,如果您有充分的理由不这样做,您可以使用描述符隐藏

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

当您尝试使用

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

8
投票

您可以为 B 中的

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

class Base():
    name = 7
    description = 8

class A(Base):
    color = 9

class B(Base):
    pass

0
投票

如果您打算将其与 Pydantic 和一些 API 验证一起使用:

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

class B(A):
    color: ClassVar[None] = None
© www.soinside.com 2019 - 2024. All rights reserved.