python的单例模式就是一个类的实例只能自始自终自能创建一次。应用场景比如说数据库的连接池。
#!/usr/bin/env python # coding=utf-8 class Foo(object): instance = None def __init__(self, name): self.name = name @classmethod def get_instance(cls): if cls.instance: return cls.instance else: obj = cls(‘hexm‘) cls.instance = obj return obj obj = Foo.get_instance() obj1 = Foo.get_instance() print(obj.name) print(obj1.name) print(Foo.instance) print(obj)
时间: 2024-10-14 04:29:51