我无法理解以下注释行。 这是一个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()。
感谢您的阅读。
答案 0 :(得分:4)
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)
。
答案 1 :(得分:2)
这一行:
method(self) #I can't umderstand this line
调用函数aaa()
。在你的函数声明中:
def aaa(self):
aaa
确实接受了一个参数(self
)。这就是你必须用method(self)
调用它的原因。
由于self.commands[0]
是一个函数,因此调用method(self)
等于:
aaa(self)
如果您还有其他问题需要评论!
答案 2 :(得分:1)
代码示例的完成方式使得更难以分辨出正在发生的事情。但是,它相当于:
child_methods = [] # a list of all the methods in `Child`
class Parent(object):
def parent_method(self):
print "parent_method() called"
method = child_methods[0]
method(self)
class Child(Parent):
def child_method(self):
print "child_method() called"
# add child_method to child_methods
child_methods.append(Child.child_method)
如您所见,child_methods[0]
实际上是函数Child.child_method
,它是一个普通函数,而不是绑定方法。它与Child
的实例无关,这就是为什么你可以而且必须自己传递self
的原因。您将从Child
实例获取绑定方法:
child_obj = Child()
bound_child_method = child_obj.child_method
如果在实例中找不到对象类型的属性,Python会查找属性,这一点并不清楚。例如:
# A dummy class to hold attributes
class Foo(object):
pass
Foo.bar = 123 # we're adding an attribute to the type itself
foo1 = Foo()
print foo1.bar # prints 123
foo1.bar = 456 # this `bar` attribute "hides" the one on the type
print foo1.bar # prints 456
foo2 = Foo()
print foo2.bar # prints the 123 from the type again
这就是为什么在您的代码示例中,commands
实际上是一个“全局”变量,它只是通过B
的实例被混淆地访问。 (如果只有B
或其子节点的对象访问此变量,但查找规则是次要问题,则这不一定是不好的做法。)
答案 3 :(得分:0)
顺便说一句,最好使用新式的类,A类(对象):...
除了类方法之外,python中的所有类方法都将self作为第一个参数。 这是关于自我的例子:
def x(first, arg):
print "Called x with arg=",arg
print first
class A(object):
some_method = x
a = A()
a.some_method("s")`
http://docs.python.org/2/tutorial/classes.html#random-remarks