【发布时间】:2018-06-14 16:37:22
【问题描述】:
考虑以下类:
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)
当bar() 作为实例方法被调用时,它会在不带参数的情况下将self 识别为实例
>>> 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:
>>> 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 中一样
>>> 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。为什么?也许是因为“最好请求宽恕而不是允许”。如果它有效,对你有好处,否则,你会在之后的某个时候遇到异常。
-
我非常有信心,一个熟练而坚定的骗子猎人可以找到这个问题的骗子,因为我很确定我以前见过它......
-
相关:stackoverflow.com/questions/3589311/… 但我不会称之为重复。
标签: python python-3.x oop