将仿函数创建为可调用 class 或嵌套函数
Create a functor as a callable class or as a nested function
在 Python 3 中,您可以像这样创建 classes:
class foo:
def __init__(self, x):
self.x=x
def __call__(self, y):
self.x = self.x + 1
return (self.x, y)
然后可以将它用作具有如下状态的仿函数:
functor = foo(5)
x = 44354234
print('(1.1) ', functor(7))
print('(1.2) ', functor(8))
print('(1.2) ', functor(9))
实际上我创建了一个 returns 函数。然而,这第一个函数实际上是一个构造函数,returns 一个可调用对象。恕我直言,这通过允许开发人员扩展 class、添加方法等打开了一堆蠕虫。此外,__init__
中的代码以某种方式自然地先于 __call__
中的代码,因为它需要被执行,而这在 class 结构中并不清楚。最后,Python 3 'way' 建议在 classes 上使用函数。
出于这个原因,我创建了一个类似 class 的函数版本,它的样板代码更少,恕我直言,读起来更自然:
def bar(x):
def f(y):
nonlocal x
x = x + 1
return (x,y)
return f
functor2 = bar(5)
x = 345234234
print('(2.1) ', functor2(7))
print('(2.2) ', functor2(8))
print('(2.3) ', functor2(9))
但是,它使用 nonlocal
并且由于我没有想到的原因可能不直观。第二种方法是好的做法,还是有危险的剔除?在 Python 3 中应该首选哪个?特别是因为我对 nonlocal
.
的使用经验很少
近年来 Python 发展政策似乎是 "let's incorporate in Python every feature from other languages" 这导致能够以各种方式完成单一任务。
所以确实没有 "preferred way" 可以做一些事情,这完全取决于开发人员想要做什么。因此,在某些情况下可能需要使用 Class
创建有状态函数并允许对其进行扩展。在 nonlocal
中使用闭包是更常见的 IMO,其中没有任何内容 non-intuitive。另一个问题是,当对方法装饰器使用这种方法时,对于函数,您将不得不编写更少的代码,而对于 类,您将不得不添加更多 'magic',因为 self
.
P.S。在 Python 中,函数可以有属性,因此另一种编写相同代码的方法是使用 x
作为 f
内部函数的属性而不是 nonlocal
,尽管这种方法不太常见然后是你描述的那些。
def bar(x):
def f(y):
f.x=f.x+1
return (f.x, y)
f.x=x
return f
编辑:向 return 语句添加额外缩进
在 Python 3 中,您可以像这样创建 classes:
class foo:
def __init__(self, x):
self.x=x
def __call__(self, y):
self.x = self.x + 1
return (self.x, y)
然后可以将它用作具有如下状态的仿函数:
functor = foo(5)
x = 44354234
print('(1.1) ', functor(7))
print('(1.2) ', functor(8))
print('(1.2) ', functor(9))
实际上我创建了一个 returns 函数。然而,这第一个函数实际上是一个构造函数,returns 一个可调用对象。恕我直言,这通过允许开发人员扩展 class、添加方法等打开了一堆蠕虫。此外,__init__
中的代码以某种方式自然地先于 __call__
中的代码,因为它需要被执行,而这在 class 结构中并不清楚。最后,Python 3 'way' 建议在 classes 上使用函数。
出于这个原因,我创建了一个类似 class 的函数版本,它的样板代码更少,恕我直言,读起来更自然:
def bar(x):
def f(y):
nonlocal x
x = x + 1
return (x,y)
return f
functor2 = bar(5)
x = 345234234
print('(2.1) ', functor2(7))
print('(2.2) ', functor2(8))
print('(2.3) ', functor2(9))
但是,它使用 nonlocal
并且由于我没有想到的原因可能不直观。第二种方法是好的做法,还是有危险的剔除?在 Python 3 中应该首选哪个?特别是因为我对 nonlocal
.
近年来 Python 发展政策似乎是 "let's incorporate in Python every feature from other languages" 这导致能够以各种方式完成单一任务。
所以确实没有 "preferred way" 可以做一些事情,这完全取决于开发人员想要做什么。因此,在某些情况下可能需要使用 Class
创建有状态函数并允许对其进行扩展。在 nonlocal
中使用闭包是更常见的 IMO,其中没有任何内容 non-intuitive。另一个问题是,当对方法装饰器使用这种方法时,对于函数,您将不得不编写更少的代码,而对于 类,您将不得不添加更多 'magic',因为 self
.
P.S。在 Python 中,函数可以有属性,因此另一种编写相同代码的方法是使用 x
作为 f
内部函数的属性而不是 nonlocal
,尽管这种方法不太常见然后是你描述的那些。
def bar(x):
def f(y):
f.x=f.x+1
return (f.x, y)
f.x=x
return f
编辑:向 return 语句添加额外缩进