问题描述
请考虑以下课程:
class Foo(object):
def bar(self):
print(self)
在Python 2 (2.7.13)中,将bar()
作为类方法调用会引发异常:
In Python 2 (2.7.13), calling bar()
as a class method raises an exception:
>>> 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)
当调用bar()
作为实例方法时,在不带参数调用时将self
识别为实例
When bar()
is called as an instance method it recognizes self
as the instance when called without arguments
>>> Foo().bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes exactly 1 argument (2 given)
>>> Foo().bar()
<__main__.Foo object at 0x10a8e1a10>
在Python 3 (3.6.0)中,将bar()
作为类方法调用时,第一个参数被接受为self
:
In Python 3 (3.6.0), when calling bar()
as a class method, the first argument is accepted as self
:
>>> Foo.bar('hello')
hello
>>> Foo.bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() missing 1 required positional argument: 'self'
调用bar()
作为实例方法的工作方式与Python 2中一样
Calling bar()
as an instance method works as in Python 2
>>> Foo().bar('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bar() takes 1 positional argument but 2 were given
>>> Foo().bar()
<__main__.Foo object at 0x104ab34a8>
推荐答案
在Python 3上,Foo.bar
只是您编写的bar
函数.它使用一个参数(恰好名为self
)并将其打印出来.您可以在任何函数上调用该函数,它将打印您传递的任何参数.
On Python 3, Foo.bar
is just that bar
function you wrote. It takes one parameter, which happens to be named self
, and prints it. You can call that function on anything, and it will print whatever argument you pass it.
在Python 2上,Foo.bar
并不完全是您编写的bar
函数.当您访问Foo.bar
时,Python会生成一个包装bar
函数的未绑定方法对象.未绑定方法对象的工作原理与bar
函数相似,主要区别在于验证其第一个参数是Foo
的实例.你可以做
On Python 2, Foo.bar
isn't quite the bar
function you wrote. When you access Foo.bar
, Python generates an unbound method object wrapping the bar
function. The unbound method object works mostly like the bar
function, with the main difference of validating that its first argument is an instance of Foo
. You could do
Foo.bar(some_foo_instance)
的作用类似于some_foo_instance.bar()
,但是调用Foo
的实现,绕过子类中的所有覆盖.但是,您不能执行Foo.bar('hello')
.
which would work like some_foo_instance.bar()
, but calling Foo
's implementation, bypassing any overrides in subclasses. You couldn't do Foo.bar('hello')
, though.
Python 3删除了未绑定的方法对象.它们不再存在.这使语言更简单,但它删除了用于执行的验证未绑定方法对象.
Python 3 removed unbound method objects. They don't exist any more. That makes the language a bit simpler, but it removes the validation unbound method objects used to perform.
这篇关于为什么实例方法在Python 3中被称为类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!