【问题标题】:How to make Python classes for independent metrics and dependent metrics?如何为独立指标和相关指标制作 Python 类?
【发布时间】:2019-11-10 00:59:03
【问题描述】:

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

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

所以在代码中我们有这样的东西:

# 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, ... 以及更多的计算方式都不同。如何将此代码结构化为类?

【问题讨论】:

  • metric_1, metric_2, ...等是Metric()类的字段还是类的实例?
  • @LockeDonohoe 它们应该是该类的实例。示例代码不是写在类中的。

标签: python class oop inheritance series


【解决方案1】:

每个复合指标都可以在它自己的子类中,每个子类都有一个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多