相关疑难解决方法(0)

为什么我不能将self作为命名参数传递给Python中的实例方法?

这有效:

>>> def bar(x, y):
...     print x, y
...
>>> bar(y=3, x=1)
1 3
Run Code Online (Sandbox Code Playgroud)

这有效:

>>> class Foo(object):
...     def bar(self, x, y):
...             print x, y
...
>>> z = Foo()
>>> z.bar(y=3, x=1)
1 3
Run Code Online (Sandbox Code Playgroud)

甚至这个工作:

>>> Foo.bar(z, y=3, x=1)
1 3
Run Code Online (Sandbox Code Playgroud)

但为什么这不起作用?

>>> Foo.bar(self=z, y=3, x=1)
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)

这使得元编程更加困难,因为它需要特殊的案例处理.我很好奇Python的语义是否是必要的,或者仅仅是实现的工件.

python methods metaprogramming python-2.x language-lawyer

5
推荐指数
1
解决办法
1410
查看次数