【发布时间】:2010-03-14 20:38:01
【问题描述】:
这行得通:
>>> def bar(x, y):
... print x, y
...
>>> bar(y=3, x=1)
1 3
这很有效:
>>> class Foo(object):
... def bar(self, x, y):
... print x, y
...
>>> z = Foo()
>>> z.bar(y=3, x=1)
1 3
即使这样也有效:
>>> Foo.bar(z, y=3, x=1)
1 3
但是为什么这在 Python 2.x 中不起作用?
>>> 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)
这使得元编程更加困难,因为它需要特殊情况处理。我很好奇它是 Python 的语义所必需的还是只是实现的工件。
【问题讨论】:
-
类名应大写,即
class Foo(object)。
标签: python methods language-lawyer metaprogramming python-2.x