我是新的python用户。因此,这可能很愚蠢。但是最好的方法是自动运行一个类(内部有多个函数)并返回给定值的结果。例如:
class MyClass():
def __init__(self,x):
self.x=x
def funct1(self):
return (self.x)**2
##or any other function
def funct2(self,y):
return y/100.0
##or any other function
def wrapper(self):
y=self.funct1()
z=self.funct2(y)
##or other combination of functions
return z
现在运行此命令,我正在使用:
run=MyClass(5)
run.wrapper()
但是我想这样运行:
MyClass(5)
它将返回一个值,可以将其保存在变量中,而无需使用包装函数。
您可以如下创建函子:
class MyClass(object):
def __init__(self,x):
self.x=x
def funct1(self):
return (self.x)**2
##or any other function
def funct2(self,y):
return y/100.0
##or any other function
def __call__(self):
y=self.funct1()
z=self.funct2(y)
##or other combination of functions
return z
对该函子的调用将如下所示:
MyClass(5)() # Second () will call the method __call__. and first one will call constructor
希望这会帮助你。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句