-1

I want this code

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 $

to print two times "K" instead of "4","48", without changing the lines

f1 = Letter("4")

and

f1 = Letter("48")

Is it possible ?

ychaouche
  • 4,242
  • 2
  • 40
  • 45
  • 2
    This doesn't make any sense. Why are you messing with `__new__`? You could just set `self.l = 'K'` in `__init__`. Maybe if you explained what you are actually trying to achieve we could help. – Bran Handley Aug 06 '13 at 16:44
  • Did you study [Is there a simple, elegant way to define Singletons in Python?](http://stackoverflow.com/q/31875) yet? – Martijn Pieters Aug 06 '13 at 16:48
  • Indeed @BranHandley, I was just making sure that __new__ ignores every argument you pass to it but the first one and that it can not influence in any way how __init__ gets called. – ychaouche Aug 07 '13 at 13:58

1 Answers1

0

If I got what your intention is:

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

will result in:

previous letter 4
previous letter 48
Saullo G. P. Castro
  • 49,101
  • 22
  • 160
  • 223