如何使用__new__设置实例变量?

时间:2013-08-06 16:35:00

标签: python

我想要这段代码

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

有可能吗?

1 个答案:

答案 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