簡體   English   中英

在python中生成沒有閉包的函數

[英]Generate functions without closures in python

現在我正在使用閉包來生成像這個簡化示例中的函數:

def constant_function(constant):
    def dummyfunction(t):
        return constant
    return dummyfunction

然后將這些生成的函數傳遞給自定義類的init方法,該類將它們存儲為實例屬性。 缺點是這使得類實例難以理解。 所以我想知道是否有辦法創建函數生成器來避免閉包。

你可以使用一個可調用的類:

class ConstantFunction(object):
    def __init__(self, constant):
        self.constant = constant
    def __call__(self, t):
        return self.constant

def constant_function(constant):
    return ConstantFunction(constant)

然后,函數的閉包狀態將轉移到實例屬性。

並不是說我推薦這個用於一般用途......但是有一種編譯和exec代碼的替代方法。 它正在生成一個沒有閉包的函數。

>>> def doit(constant): 
...   constant = "def constant(t):\n  return %s" % constant
...   return compile(constant, '<string>', 'exec')
... 
>>> exec doit(1)
>>> constant(4)
1
>>> constant

請注意,要在封閉函數或類中(即不在全局命名空間中)執行此操作,您還必須將適當的命名空間傳遞給exec 請參閱: https//docs.python.org/2/reference/simple_stmts.html#the-exec-statement

還有雙lambda方法,它不是真正的閉包,嗯,有點......

>>> f = lambda x: lambda y:x
>>> g = f(1)
>>> g(4)
1
>>> import dill
>>> _g = dill.dumps(g)
>>> g_ = dill.loads(_g) 
>>> g_(5)
1

你似乎擔心腌制類似閉合的物體的能力,所以如果你使用dill ,你甚至可以看到雙羔羊是可腌制的。 類實例也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM