【问题标题】:How can I access a property of the base class of another base class?如何访问另一个基类的基类的属性?
【发布时间】:2021-07-01 19:54:47
【问题描述】:

假设,我有以下情况:

class TopBaseClass:
    ... ...
    ... ...
    @property
    def top_property(self):
        return self.__top_property
    
    @top_property.setter
    def top_property(self, top_property):
        self.__top_property = top_property

class IntermediateBaseClass(TopBaseClass):
    ...

class LowestClass(IntermediateBaseClass):
    ... ...
    ... ...
    def lowest_function(self):
        something = ""

        ... ...
         
        return something

现在,我想从lowest_function() 访问top_property

我该怎么做?

我尝试了以下方法,但没有成功:

something = str(super().super().top_property)

它给了我一个错误。

那么,该怎么做呢?

【问题讨论】:

  • 只需使用self.top_property。这就是继承的工作原理。

标签: python inheritance properties


【解决方案1】:

你想做的事:

something = self.top_property

属性是实例的一部分,可以直接引用。 getter 将用于检索值。

【讨论】:

  • 那么什么时候使用super()
  • 当方法名被覆盖时使用 super。因此,如果您在超类中有一个方法或属性,而在您的子类中有相同的命名成员,您将使用 super 来调用基类中的那个(它强制引用去那里而不是子类)
猜你喜欢
  • 2011-11-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2020-02-18
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多