Why can instance methods be called as class methods in Python 3?
考虑以下类别:
1 2 3 | class Foo(object): def bar(self): print(self) |
在python 2(2.7.13)中,作为类方法调用
1 2 3 4 5 6 7 8 9 | >>> 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) |
当调用
1 2 3 4 5 6 7 | >>> 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)中,当调用
1 2 3 4 5 6 7 | >>> 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' |
作为实例方法调用
1 2 3 4 5 6 7 | >>> 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上,
在python 2上,
1 | Foo.bar(some_foo_instance) |
它与
python 3删除了未绑定的方法对象。它们不再存在了。这使得语言简单了一点,但它删除了用于执行的验证未绑定方法对象。