以下是我倾向于在这里和那里使用的“模式”的略微简化示例。
class Indicator(object):
def __init__(self):
self.list1 = []
instances = {}
@classmethod
def get_instance(cls, date, hour, hostname, action):
if (date, hour, hostname, action) in Indicator.instances:
i = Indicator.instances[(date, hour, hostname, action)]
else:
i = cls()
Indicator.instances[(date, hour, hostname, action)] = i
return i
def add_data_point(self, foo):
self.list1.append(foo)
def get_avg(self):
return sum(self.list1) / len(self.list1)
Indicator.get_instance("2015-01-01", "12", "host1", "foo1").add_data_point(23)
Indicator.get_instance("2015-01-01", "12", "host1", "foo1").add_data_point(-5)
Indicator.get_instance("2015-01-01", "12", "host1", "foo1").add_data_point(12)
Indicator.get_instance("2015-01-01", "12", "host1", "foo1").add_data_point(6)
Indicator.get_instance("2015-01-01", "12", "host2", "foo1").add_data_point(2322)
Indicator.get_instance("2015-01-01", "12", "host2", "foo1").add_data_point(-52)
Indicator.get_instance("2015-01-01", "12", "host2", "foo1").add_data_point(232)
Indicator.get_instance("2015-01-01", "12", "host2", "foo1").add_data_point(34)
for indicator_id in Indicator.instances:
print('For {0} average is {1}'.format(indicator_id, Indicator.instances[indicator_id].get_avg()))
由于这似乎是我经常做的事情,我很想相信有更好/更简单的方法来使用python(2.6)。有吗?
答案 0 :(得分:0)
我认为这会更好。更新逻辑以进行初始化。
#-*- coding:utf-8 -*-
#!/usr/bin/env python
class Indicator(object):
def __init__(self):
self.list1 = []
instances = {}
@classmethod
def get_instance(cls, hostname, date="2015-01-01", hour="12", action="fool"):
if not (date, hour, hostname, action) in Indicator.instances:
Indicator.instances[(date, hour, hostname, action)] = cls() # you only need to initialize when there is no match
return Indicator.instances[(date, hour, hostname, action)]
def add_data_point(self, foo):
self.list1.append(foo)
def get_avg(self):
return sum(self.list1) / len(self.list1)
# use list comprehension to initialize instances
[i.add_data_point(x) for i,x in zip(map(Indicator.get_instance(), ['host1', 'host1', 'host1', 'host1', 'host2', 'host2', 'host2', 'host2']), [23, -5, 12, 6, 2322, -52, 232, 34])]
for indicator_id in Indicator.instances:
print('For {0} average is {1}'.format(indicator_id, Indicator.instances[indicator_id].get_avg()))