-1

我想要这个代码

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")

可能吗 ?

4

1 回答 1

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
于 2013-08-07T04:20:22.980 回答