str1 = "k:1|k1:2|k2:3|k3:4" def str2dict(str1): dict1 = {} for iterms in str1.split('|'): key,value = iterms.split(':') dict1[key] = value return dict1 #字典推导式 d = {k:int(v) for t in str1.split("|") for k, v in (t.split(":"), )}
17.python如何实现单例模式?请写出两种实现方式?
第一种方法:使用装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def singleton(cls): instances = {} def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper @singleton class Foo(object): pass foo1 = Foo() foo2 = Foo() print(foo1 is foo2) # True
第二种方法:使用基类 New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance class Foo(Singleton): pass