【问题标题】:How to avoid use of self.__dict__ in a class [duplicate]如何避免在类中使用 self.__dict__ [重复]
【发布时间】:2016-10-10 23:15:05
【问题描述】:

有人告诉我应该避免在我的代码中使用self.__dict__,但我找不到其他方法来解决我正在尝试做的事情。我刚开始使用类,所以不太清楚如何做到这一点。

class variable( object ):
    def __init__( self, json_fn, *args, **kwargs ):

        self.metrics = self.getmetrics(json_fn)
        for metric in self.metrics :
            self.__dict__[metric] = self.get_metric_dataframes(metric)

    def get_metric_dataframes( self , metric_name ):
        '''extract and return the dataframe for a metric'''

所以我的对象“变量”对于存储在 json 中的不同指标具有不同的数据帧。我希望能够做 variable.temperature, variable.pressure , variable.whatever 而不必写:

self.temperature = self.get_metric_dataframes(temperature)
self.pressure = self.get_metric_dataframes(pressure)
self.whatever = self.get_metric_dataframes(whatever)

由于所有数据帧都是使用以度量作为参数的相同函数提取的。这就是为什么我遍历指标并使用

self.__dict__[metric] = self.get_metric_dataframes(metric)

所以知道我永远不会更新任何这些数据帧(我在代码中使用它们的副本,但不想更新对象的值)。

还有其他解决方案吗?

我可以做的另一种方法是构建一个字典,其中所有指标作为键和数据框作为值并将其存储在self.metric,然后我可以使用object.metric['temperature'] 调用它,但我更愿意使用object.temperature马上,我很想知道这是否可以做到。

感谢您的帮助!

【问题讨论】:

  • 你或许可以使用setattr(),但我不知道你为什么被告知要避免使用self.__dict__

标签: python class dictionary


【解决方案1】:

如果每个metric 是一个字符串,您可以使用setattr 代替直接访问您的实例字典:

for metric in self.metrics:
     setattr(self, metric, self.get_metric_dataframes(metric))

【讨论】:

  • 谢谢,这正是我想要的
【解决方案2】:

有几种解决方案:

  • 使用__getattr__,但您可能会遇到困难(实施可能不简单)
  • 使用属性:优雅而经典的解决方案,
  • 使用描述符:如果您对此很熟悉,可能很难调试。

最后,您使用__dict__ 的解决方案非常好。你也可以使用getattr/setattr

另一种解决方案是将您的指标存储在您自己的字典中:

self.metric_dict = {metric: self.get_metric_dataframes(metric) for metric in metrics}

然后定义属性来访问这个字典之类的属性

@property
def temperature(self):
    return self.metric_dict["temperature"]

等等……

【讨论】:

  • 这似乎比摩西的回答要多一些工作,但这也是一种有趣的方式,谢谢,我会更深入地研究一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
相关资源
最近更新 更多