因此,我创建了一个python库,用于计算时间序列(here)之间的错误指标。当我第一次创建该库时,我是一位初学者,以前的经验几乎为零,因此对于每个错误度量,我只是将其编写为一个函数。今天,我认为如果将每个错误度量标准表示为一个类可能会很好,因此用户可以执行以下操作。
# Name of the package
import HydroErr as he
he.r_squared.description # Would return out a brief metric description
我想保持旧的API语法不变,否则它将破坏所有旧代码。传递模拟和观察到的数据时,必须看起来像这样。
import HydroErr as he
import numpy as np
he.r_squared(np.array([1, 2, 3]), np.array([1.1, 1.21, 1.3]))
# Out: 0.9966777408637874
我不太确定该怎么做,更重要的是我是否应该这样做。任何帮助将不胜感激。
答案 0 :(得分:2)
要在一个类中打开一个函数,可以使用__call__
方法:
def function(param):
pass
# Becomes
class MyClass:
def __call__(self, param):
pass
def other_method(self):
pass
function = MyClass()
两者都可以这样使用:function(42)
答案 1 :(得分:1)
您没有将这些函数转换为可以正常工作的类:
def r_squared(x, y):
""" Do things... """
return 56
r_squared.description = r_squared.__doc__
如果有很多这样的功能,您可以编写一个装饰器:
def add_description(fn):
fn.description = fn.__doc__
@add_description
def r_squared(x, y):
""" Do things... """
return 56