【问题标题】:Invoking other class/object methods from inside the class从类内部调用其他类/对象方法
【发布时间】:2021-12-07 12:01:50
【问题描述】:

假设我有以下代码:

class Classy:
    def other(self):
        print("other")

    def method(self):
        print("method")
        self.other()


obj = Classy()
obj.method()

输出:

method
other

所以我从类内部调用另一个对象/类方法。我在“方法”方法中调用另一个方法。

现在如果我运行以下代码:

class Classy:
    def other(self):
        print("other")

    def method(self):
        print("method")
        Classy.other(self)


obj = Classy()
obj.method()

输出是一样的。现在我的问题是:这两者有什么区别?

我不确定这是否只是一种不同的调用方式 - 所以它基本上是相同的 - 或者逻辑上是否存在差异。如果是的话,我会对一个区别很重要的例子感兴趣。

【问题讨论】:

  • 什么是self 是一个从Classy继承覆盖other的类的实例?
  • 这能回答你的问题吗? What is the purpose of the word 'self'?
  • 代码:Classy.other(self) 是 python 将:self.other() 变成的。使用后者更常规。
  • @quamrana 只是一个约定俗成的问题,在任何重要的情况下,行为都可能不同。

标签: python python-3.x oop


【解决方案1】:

让我们进行设置,以便我们可以并排运行它们:

class Classy:
    def other(self):
        print("Classy.other")
    def method(self):
        print("Classy.method")
        self.other()

class NotClassy:
    def other(self):
        print("NotClassy.other")
    def method(self):
        print("NotClassy.method")
        NotClassy.other(self)

到目前为止,一切都很好:

>>> Classy().method()
Classy.method
Classy.other
>>> NotClassy().method()
NotClassy.method
NotClassy.other

但是如果 inheritance 参与进来怎么办,就像在 中经常发生的那样?让我们定义两个继承method但覆盖other的子类:

class ClassyToo(Classy):
    def other(self):
        print("ClassyToo.other")

class NotClassyToo(NotClassy):
    def other(self):
        print("NotClassyToo.other")

然后事情就有点问题了;尽管子类的实现几乎相同,并且父类的行为似乎完全相同,但这里的输出却不同:

>>> ClassyToo().method()
Classy.method
ClassyToo.other
>>> NotClassyToo().method()
NotClassy.method
NotClassy.other  # what about NotClassyToo.other??

通过直接调用NotClassy.other,而不是调用self 上的方法,我们绕过了NotClassyToo 中的覆盖实现。 self 可能并不总是定义该方法的类的实例,这也是您看到 super 被使用的原因 - 您的类应该合作继承以确保正确的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2015-06-16
    相关资源
    最近更新 更多