我无法理解以下注释行。 这是一个 Python 程序。
class B:
def bbb(self):
method = self.commands[0]
method(self) #I can't umderstand this line
class A(B):
def aaa(self):
print 'aaa was called'
commands = [aaa]
c = A()
c.bbb()
输出: aaa 被称为
我认为上面的 aaa 方法不需要参数。 但是要运行这段代码,我需要将“self”传递给 aaa 参数。为什么?有文档解释这个问题吗?这个问题属于什么类别?
非常欢迎任何简单的代码。 因为我的英语水平太低了。 所以也欢迎改进这个问题。
我在阅读 cpython/Lib/distutils/cmd.py:Command.get_sub_commands() 时遇到了这个问题。
感谢阅读。
请您参考如下方法:
哇,这写得令人困惑。从代码本身向后工作:
c = A()
创建 A 的实例。查看 A:
def aaa(self):
print 'aaa was called'
commands = [aaa]
这写的有点困惑;这样更有意义:
def aaa(self):
print 'aaa was called'
commands = [aaa]
定义一个方法 aaa,然后是一个类变量 commands,其中包含 aaa 作为元素。现在,看看程序的下一行:
c.bbb()
由于A没有bbb并且A继承自B,我们引用B:
class B:
def bbb(self):
method = self.commands[0]
method(self)
因为我们已经确定commands是[aaa],所以第一行的意思是method = aaa。所以第二行实际上是 aaa(self)。
