python - python 类中自动返回值

标签 python python-2.7

我是一个新的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/

相关文章:

python - Python中从一个类中调用多个函数而无需每次都重复类名

python - 替换/删除 pandas 数据中的某些文本?

python - 改变字典的哈希函数

python - 不同子解析器中的常见位置参数

python - 如何将外键提交到表单中? python /Django

python - 在新 Mac 上安装 psd-tools 的挑战

python - 如何通过类变量找到类的具体实例?

python - 未就绪 : File Not Uploaded when adding to Facebook Custom Audience

python - 如何通过使用arduino开发板和python脚本从电位计连续获取电压信号来调整音频文件的音量

python - 列表中出现频率最高的数字