小编vii*_*iis的帖子

为什么在Python 3中可以将实例方法作为类方法调用?

考虑以下课程:

class Foo(object):
    def bar(self):
        print(self)
Run Code Online (Sandbox Code Playgroud)

在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)
Run Code Online (Sandbox Code Playgroud)

bar()作为实例方法调用时,它self在没有参数的情况下被识别为实例

>>> Foo().bar('hello')
Traceback (most recent …
Run Code Online (Sandbox Code Playgroud)

python oop python-3.x

3
推荐指数
1
解决办法
100
查看次数

标签 统计

oop ×1

python ×1

python-3.x ×1