考虑以下课程:
class Foo(object):
def bar(self):
print(self)
Run Code Online (Sandbox Code Playgroud)
在Python 2(2.7.13)中,bar()作为类方法调用会引发异常:
>>> Foo.bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got str instance instead)
>>> Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud)
当bar()作为实例方法调用时,它self在没有参数的情况下被识别为实例
>>> Foo().bar('hello')
Traceback (most recent …Run Code Online (Sandbox Code Playgroud)