Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在Python3中实例方法可以被称为类方法?_Python_Python 3.x_Oop - Fatal编程技术网

为什么在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)