首页 > 解决方案 > Python:当我覆盖它们时,基类属性和方法会发生什么?他们还“存在”吗?

问题描述

说我有

class Base:
    def __init__(self):
       self.x = 5

我得出

class Derived(Base):
    def __init__(self):
       self.x = 4

现在,我仍然想访问派生类中x的原始内容。Base但是我覆盖了它,所以它永远消失了吗?或者我还能在某个地方找到它吗?

请注意,我不能调用x其他东西的派生值,因为方法Base会调用self.x,并且如果该方法是从 -object 调用的,则self.x必须如此!4Derived

上面的例子是针对一个变量的,但同样的问题也适用于 in 中的方法,在Base中被覆盖Derived

标签: pythoninheritance

解决方案


如果您在 init 之外包含属性,它将是一个类绑定参数。这样您就可以访问Base.x因此,您创建的派生的每个实例都将具有x根据 init 的属性,并且您可以访问Base属性。

>>> class Base:
...     x = 5
>>> class Derived(Base):
...     def __init__(self):
...             self.x = 4
>>> derived_instance = Derived()
>>> derived_instance.x
4
>>> Base.x
5
>>>

推荐阅读