为了建立我个人的编程风格,我希望能够像调用python函数一样调用python类。我的意思是:考虑这个函数:
def Factorial(n):
if n == 0:
return 1
else:
return n * Factorial(n - 1)
这是一个在调用Factorial(4)时输出24的函数。
现在让我们考虑一个类:
class Factorial:
def __call__(n):
if n == 0:
return 1
else:
return n * Factorial()(n - 1)
此代码的工作方式与前面的代码相同,但在调用时,您可以编写以下代码:
Factorial()(4) # which outputs 24
现在我的问题是,你如何才能做到这一点:
Factorial(4) # just that, and output 24, from THE object.
谢谢!
发布于 2018-07-21 02:07:10
使用self
。
class Factorial:
def __call__(self, n):
if n == 0:
return 1
else:
return n * self(n - 1)
f = Factorial()
f(3)
# 6
f(5)
# 120
在此基础上,您可以轻松地在__new__
构造函数中添加一个起始值。
class Factorial:
def __new__(cls, value=None):
instance = super().__new__(cls)
if value is None:
return instance
else:
return instance(value)
def __call__(self, n):
if n == 0:
return 1
else:
return n * self(n - 1)
现在你可以
Factorial(5)
# 120
f = Factorial()
f(5)
# 120
发布于 2018-07-21 02:00:20
使用一个构造函数(在Python语言中是__init__ ),如下所示:
class Factorial: def __init__(self, n): // code here
发布于 2018-07-21 02:16:31
您可以覆盖__new__
方法:
class Factorial:
def __new__(cls, n):
if n == 0:
return 1
else:
return n * Factorial(n - 1)
虽然上面的解决方案有效,但我更喜欢基于装饰器的解决方案,它不那么神奇,更直观和明确:
def function_factory(cls):
return cls()
@function_factory
class Factorial:
def __call__(self, n):
if n == 0:
return 1
else:
return n * Factorial(n - 1)
https://stackoverflow.com/questions/51447968
复制相似问题