【问题标题】:Return values automatically in python class在 python 类中自动返回值
【发布时间】:2018-10-09 12:55:10
【问题描述】:

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

这将返回一个值并且可以保存在变量中而无需使用包装函数。

【问题讨论】:

  • 如果你不想保留它的实例就不要使用一个类,它似乎是你想要的一个函数
  • 1.您可以在__init__ 中调用wrapper(但请记住,__init__ 不能返回值,因此您仍然需要使用属性来存储结果)。 2. 我不确定MyClass 是否值得/应该是一门课。

标签: python python-2.7


【解决方案1】:

您可以创建如下仿函数:

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

希望这会对你有所帮助。

【讨论】:

    【解决方案2】:

    因此,当您编写 MyClass(5) 时,您正在创建一个 那个 类的新实例:MyClass,所以简短的回答是,您确实需要包装器,因为当您实例化类时,它必然会返回对象而不是某个值。

    如果您只想根据输入返回一个值(比如5),请考虑改用function

    函数如下:

       def my_func(x):
            y = x**2
            z = y/100.0
            return z
    

    使用类有很多原因,请参阅此答案 https://stackoverflow.com/a/33072722/4443226 -- 但如果您只关心运算/方程/函数的输出,那么我会坚持使用函数。

    【讨论】:

      【解决方案3】:

      __init__ 方法应该返回 None
      documentation link

      init()

      不能返回任何非 None 值

      【讨论】:

        猜你喜欢
        • 2012-09-06
        • 2011-09-07
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-04
        • 2016-01-10
        • 1970-01-01
        相关资源
        最近更新 更多