我想要这段代码
class Letter(object):
def __init__(self,l):
self.l = l
def __new__(cls,*args,**kw):
if hasattr(Letter,"L"):
return Letter.L
Letter.L = object.__new__(cls,"K",**kw)
return Letter.L
f1 = Letter("4")
print "f1 value was",f1.l
f2 = Letter("48")
print "Although I didn't change anything in f1, its value is now",f1.l
print f1 is f2
>> chaouche@karabeela ~/CODE/TEST/PYTHON $ python singleton.py
>> f1 value was 4
>> Although I didn't change anything in f1, its value is now 48
>> True
>> chaouche@karabeela ~/CODE/TEST/PYTHON $
打印两次“K”而不是“4”,“48”,而不更改行
f1 = Letter("4")
和
f1 = Letter("48")
有可能吗?
答案 0 :(得分:0)
如果我得到你的意图:
class Letter(object):
cL = None
def __init__(self,L):
if not Letter.cL:
Letter.cL = L
else:
print 'previous letter', Letter.cL
Letter.cL = L
self.L = L
f1 = Letter("4")
f2 = Letter("48")
f3 = Letter("52")
将导致:
previous letter 4
previous letter 48