我是一个新的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
希望这对您有帮助。
关于python - python 类中自动返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52721597/