【发布时间】: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