因此,这更是编写干净的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
这怎么办?如果存在重复的问题,请在评论中告知我。
答案 0 :(得分:2)
您可以像这样使用方法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)()
答案 1 :(得分: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...