有人可以告诉我为什么这是不正确的单身人士模式:
class preSingleton(object):
def __call__(self):
return self
singleton = preSingleton()
# singleton is actually the singleton
a = singleton()
b = singleton()
print a==b
a.var_in_a = 100
b.var_in_b = 'hello'
print a.var_in_b
print b.var_in_a
Run Code Online (Sandbox Code Playgroud)
编辑:上面的代码打印:
True
hello
100
Run Code Online (Sandbox Code Playgroud)
非常感谢你
第二部分
也许这更好?
class Singleton(object):
def __new__(cls):
return cls
a = Singleton()
b = Singleton()
print a == b
a.var_in_a = 100
b.var_in_b = 'hello'
print a.var_in_b
print b.var_in_a
Run Code Online (Sandbox Code Playgroud)
编辑:上面的代码打印:
True
hello
100
Run Code Online (Sandbox Code Playgroud)
再次感谢.
单身实际上很容易用Python制作.诀窍是让模块为你做封装而不是上课.
如果您想假装模块是类的实例,则可以执行以下操作
import some_module
class SomeClass(object):
def __init__(self):
self.singleton = some_module
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2065 次 |
| 最近记录: |