python - 如何为独立指标和相关指标创建Python类?

标签 python class oop inheritance series

我有一些指标需要转化为类。

  • 每个指标都有一个名称(字符串)、一个单位(字符串)和一个(一系列值)
  • 某些指标是依赖于其他指标并根据其他指标计算的,并且还需要具有这些指标的名称以供以后引用。

所以在代码中我们有这样的内容:

# normal metrics 
metric_1 = series_1
metric_2 = series_2
metric_3 = series_3

# calculated metrics
# each needs to know the names of other metrics it uses to calculate 
metric_4 = metric_1 + metric_2
metric_5 = metric_2 - metric_3 * 100
metric_6 = metric_1 + metric_2 + metric_3

我尝试为独立指标创建一个类 Metric() ,并为这些相关指标创建一个子类 CalMetric() 。但问题是 metric_4、metric_5、metric_6 等的计算方式都不同。如何将这段代码构建为类?

最佳答案

每个复合指标都可以位于其自己的子类中,并具有每个子类特有的compute方法:

class Metric4(Metric):

    def __init__(self, metric_1, metric2):
        self.metric_1 = metric_1
        self.metric_2 = metric_2

    def compute(self):
        return self.metric_1 + self.metric_2

关于python - 如何为独立指标和相关指标创建Python类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58784916/

相关文章:

c# - 一种面向对象代码分析的思路

node.js - 向 Node.js 中的嵌套接口(interface)添加属性

python - 如何打印以特定字符开头的列表中的值

python - 使用独立于数组维度的填充来切片 numpy ayarray

C++ 类重载 : is it possible to make compiler see which one to use based on template?

oop - nextTick 在类中的用法

python - 如何根据索引替换子字符串?

python - 如何将 EXIF/其他元数据插入存储在内存缓冲区中的 JPEG?

javascript - 激活容器类时触发内部类为 'this'

this.x = x; 的 C++ 非类作用域替换;