【发布时间】: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类,然后是Sine和Cosine等子类,它们具有evaluate和integrate等成员函数。 — 或者你有一个包装实际函数的 closure。但我认为这不会奏效,因为它们的差异化是不同的。 — 使用 SymPy 之类的东西,它可以直接为您提供差异化。或者像 Autograd 这样的东西。 -
检查是否为:stackoverflow.com/questions/4246000/…您问题的答案
-
@MartinUeding SYmPy 是有问题的,我无法找出错误,但为了获得更高的精度,它会为不同的运行提供可变的结果。就像您每次都单击运行按钮并且图形在变化,即使您在任何地方都没有随机函数。
标签: python python-3.x