1 class eager_meta(type): 2 def __init__(clz, name, bases, dic): 3 super(eager_meta, clz).__init__(name, bases, dic) 4 clz._instance = clz() 5 6 class singleton_eager(object): 7 __metaclass__ = eager_meta 8 9 @classmethod 10 def instance(clz): 11 return clz._instance 12 13 14 class singleton_lazy(object): 15 __instance = None 16 @classmethod 17 def instance(clz): 18 if clz.__instance is None: 19 clz.__instance = singleton_lazy() 20 return clz.__instance
PS:在python中,這樣使用單例模式不是很pythonic,更好的辦法可見在stackoverflow上的這篇文章《creating-a-singleton-in-python》。另外在多線程環境下,要實現線程安全的單例仍是很複雜的,具體討論可參見iteye上的分析。javascript
1 ret = any(self.calc_and_ret(e) for e in elements) 2 def self.calc_and_ret(self, e): 3 # do a lot of calc here which effect self 4 return True(or False)
1 for x in [i*i for i in xrange(10000)] 2 # do sth with i 3 4 for x in (i*i for i in xrange(10000)] 5 # do sth with i
1 class Fruit: 2 def __init__(self, item): 3 self.item = item 4 5 class Fruits: 6 def __init__(self): 7 self.items = {} 8 9 def get_fruit(self, item): 10 if item not in self.items: 11 self.items[item] = Fruit(item) 12 13 return self.items[item] 14 15 if __name__ == '__main__': 16 fruits = Fruits() 17 print(fruits.get_fruit('Apple')) 18 print(fruits.get_fruit('Lime'))