【问题标题】:How do I use an anonymous function within a class method in Python (closure)?如何在 Python(闭包)的类方法中使用匿名函数?
【发布时间】:2011-04-08 15:13:03
【问题描述】:
class Test:

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

        write()

x = Test()
x.somemethod()

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

当我运行该代码时,我收到以下错误:

TypeError: somemethod() takes exactly 2 arguments (1 given)

我做错了什么? self 是否被传递给 write()? :/

【问题讨论】:

标签: python closures anonymous-function


【解决方案1】:

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

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

所以我相信你一定是有一些转录错误,或者其他什么。当您完全运行我在这里显示的代码时,您会看到什么? (在所有平台上的 Python 2.4、2.5、2.6、2.7 中工作方式相同)。

【讨论】:

  • 我的 bug 似乎在别处……谢谢你让我清醒
【解决方案2】:

它也适用于我:

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

我认为您可能使用了制表符空格,或者您的标识错误

【讨论】:

    猜你喜欢
    • 2019-08-31
    • 2011-12-25
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2017-01-11
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多