【发布时间】: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