如何在Python中的类方法中使用匿名函数(闭包)?

如何在Python中的类方法中使用匿名函数(闭包)?,python,closures,anonymous-function,Python,Closures,Anonymous Function,write()是通过somemethod()多次使用的函数。somemethod()是类中唯一需要使用它的函数,因此在somemethod()之外定义它似乎很愚蠢。关闭似乎是一条路要走 当我运行该代码时,会出现以下错误: class Test: def somemethod(self): def write(): print 'hello' write() x = Test() x.somemethod() 我做错了什么?s

write()是通过somemethod()多次使用的函数。somemethod()是类中唯一需要使用它的函数,因此在somemethod()之外定义它似乎很愚蠢。关闭似乎是一条路要走

当我运行该代码时,会出现以下错误:

class Test:

    def somemethod(self):
        def write():
            print 'hello'

        write()

x = Test()
x.somemethod()

我做错了什么?
self
是否通过了write()/

我发现无法重现您报告的问题:

TypeError: somemethod() takes exactly 2 arguments (1 given)
所以我相信你一定是做了些抄写错误之类的事情。当您运行我在这里展示的代码时,您看到了什么?(在所有平台上,Python 2.4、2.5、2.6、2.7的工作原理相同)。

它也适用于我:

>>> class Test(object):
...   def somemethod(self):
...     def write():
...       print 'hello'
...     write()
... 
>>> x = Test()
>>> x.somemethod()
hello
>>> 

我想您可能使用了制表符和空格,或者您的识别错误

可能重复了我与的连接,因此在我尝试发布时出错。好像是双柱的。抱歉>。不用担心。我已经标记了这些问题,其中一个问题将很快被版主删除或合并。-1为双贴,不清理。我的错误似乎在别处。。。谢谢你让我清醒过来
>>> class Test:
...     def somemethod(self):
...         def write():
...             print 'hello'
...         write()
... 
>>> 
>>> x = Test()
>>> x.somemethod()
hello
>>>