【问题标题】:Replacing multiple `if-else` with single `if-else` in a class [duplicate]用一个类中的单个“if-else”替换多个“if-else”[重复]
【发布时间】:2019-02-24 08:59:30
【问题描述】:

所以这更像是一个编写干净的 Python3 代码的小问题。假设我有一个类function,它可以根据用户输入创建许多函数类型。

import numpy as np

class functions(object):

    def __init__(self, typeOfFunction, amplitude, omega, start = None, stop = None,
                 pulsewidth = None):
        self.typeOfFunction = typeOfFunction
        self.amplitude = amplitude
        self.omega = omega
        self.period = 2 * np.pi/omega
        self.start = start
        self.stop = stop
        self.pulsewidth = pulsewidth

    def sine_function(self, t):
        func = self.amplitude * np.sin(self.omega*t)
        return func

    def cosine_function(self, t):
        func = self.amplitude * np.cos(self.omega*t)
        return func

    def unit_step_function(self, t):
        func = self.amplitude * np.where(t > self.start, 1, 0)
        return func

现在我的问题是让我们说我们要编写其他 3 个函数:

  • 差异化
  • 集成
  • 在给定时间进行评估。

现在我的问题是,在每个函数中我都必须设置如下条件:

    def evaluate_function(self, time):
        if(self.typeOfFunction == 'sine'):
            funcValue = self.sine_function(time)
        elif(self.typeOfFunction == 'cosine'):
            funcValue = self.cosine_function(time)
        elif(self.typeOfFunction == 'unit_step_function'):
            funcValue = self.unit_step_function(time)

我只想在 __init__ 方法中执行一次,并且在后续步骤中只需传递参数而不是编写 if-else

def __init__(self, typeOfFunction, amplitude, omega, start = None, stop = None,
                 pulsewidth = None):
        self.typeOfFunction = typeOfFunction
        self.amplitude = amplitude
        self.omega = omega
        self.period = 2 * np.pi/omega
        self.start = start
        self.stop = stop
        self.pulsewidth = pulsewidth

        #DO SOMETHING THAT MAKES THE TYPE OF FUNCTION EMBEDDED
         IN THE CLASS IN A CLASS VARIABLE

然后:

def evaluate_function(self, time):
      value = self.doSomething(time)
      return value

如何做到这一点?如果存在重复问题,请在 cmets 中通知我。

【问题讨论】:

  • 您可以使用多态性来拥有一个抽象的Function 类,然后是SineCosine 等子类,它们具有evaluateintegrate 等成员函数。 — 或者你有一个包装实际函数的 closure。但我认为这不会奏效,因为它们的差异化是不同的。 — 使用 SymPy 之类的东西,它可以直接为您提供差异化​​。或者像 Autograd 这样的东西。
  • 检查是否为:stackoverflow.com/questions/4246000/…您问题的答案
  • @MartinUeding SYmPy 是有问题的,我无法找出错误,但为了获得更高的精度,它会为不同的运行提供可变的结果。就像您每次都单击运行按钮并且图形在变化,即使您在任何地方都没有随机函数。

标签: python python-3.x


【解决方案1】:

您可以像这样使用 getattr(CLASS_OBJECT, METHOD_ORVARIABLE_NAME) 方法:

method = getattr(self, self.typeOfFunction)

然后调用方法:

method()

或简称:

getattr(self, self.typeOfFunction)()

你也可以检查你得到的属性是否存在:

if hasattr(self, self.typeOfFunction):
    getattr(self, self.typeOfFunction)()

【讨论】:

    【解决方案2】:

    我想你想要一个带有 dict 的映射。

    类似这样的:

    class functions(object):
    
        def evaluate_function(self, which, time):
            mapping = {'sine': self.sine_function,
                       'cosine': self.cosine_function,
                       # ...more functions here...
                      }
            return mapping[which](time)
    
        # rest of class here...
    

    【讨论】:

      猜你喜欢
      • 2012-10-23
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2021-03-16
      相关资源
      最近更新 更多