为什么在Python3中实例方法可以被称为类方法?
考虑以下类别:为什么在Python3中实例方法可以被称为类方法?,python,python-3.x,oop,Python,Python 3.x,Oop,考虑以下类别: class Foo(object): def bar(self): print(self) 在Python 2中(2.7.13),调用bar()作为类方法会引发异常: >>> Foo.bar('hello') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method bar(
class Foo(object):
def bar(self):
print(self)
在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)
在Python 3(3.6.0)中,当调用bar()
作为类方法时,第一个参数被接受为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'
在Python3上,
Foo.bar
就是您编写的bar
函数。它接受一个名为self
的参数,并将其打印出来。您可以对任何对象调用该函数,它将打印您传递给它的任何参数
在Python2上,Foo.bar
不是您编写的bar
函数。当您访问Foo.bar
时,Python会生成一个未绑定的方法对象,该对象包装bar
函数。unbound method对象的工作原理与bar
函数类似,主要区别在于验证其第一个参数是否是Foo
的实例。你可以
Foo.bar(some_foo_instance)
它的工作原理类似于some\u foo\u instance.bar()
,但调用foo
的实现,绕过子类中的任何重写。但是,您不能执行Foo.bar('hello')
他们已经不存在了。这使语言变得更简单,但它删除了用于执行的未绑定验证方法对象。好问题。似乎他们删除了检查python 3。为什么?也许是因为“请求原谅比请求允许更好”。如果它有效,对你有好处,否则,你会在以后的某个时候得到一个例外。我很有信心,一个有适当技能和决心的傻瓜猎人可以找到这个问题的傻瓜,因为我很确定我以前见过它……相关:但我不会称之为复制品。
>>> 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>
Foo.bar(some_foo_instance)