-1

Why is the object not getting deleted and reinstantiated when I call the del function in the below code?

class A:
    def __init__(self, a={}):
        if not ('1' in a):
            a['1']=1
        else:
            a['1']+=1

        print (a['1'])

    def __del__(self):
        del self.a

for i in range (5):
    a=A()

output:

1,2,3,4,5

expected output:

1,1,1,1,1
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Prasun
  • 1
  • 1
  • Where do you call the "del" function? (There is no function called `del`, do you mean `__del__`?) – mkrieger1 Jun 17 '20 at 12:36
  • Can you explain *why* you expected `1,1,1,1,1` as output? – mkrieger1 Jun 17 '20 at 12:38
  • Since you already have answer to the problem you are facing below, just looking over what you are trying to achieve there, take a look at collections.defaultdict instead – Bogdan Jun 17 '20 at 12:39
  • Thanks all for the answers. What i want to achieve is once the object is created then " if not ('1' in a): a['1']=1 " this line should get executed every time since every time the __del__ would get called and the object would cease to exist. Isn't it expected that __del__ would just delete the object every time it's called? Please correct me if I am wrong. – Prasun Jun 17 '20 at 13:13
  • **If** `__del__` is called. Where do you expect that it is called? – mkrieger1 Jun 17 '20 at 13:14
  • See https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it – mkrieger1 Jun 17 '20 at 13:16

1 Answers1

2

When you use a mutable item as default param in the init of a class it will be shared across all instances that created in the same scope. You need to create a dict in each init of class instances like

class A:
    def __init__(self, a=None):
        a = {} if not a else a
        if not ('1' in a):
            a['1']=1
        else:
            a['1']+=1

        print (a['1'])


for i in range(5):
    a=A()

Output

1
1
1
1
1
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
  • There's also no need to define `__del__` in this case; if the instance of `A` can be garbage-collected, so can the `dict` referenced (only) by its `a` attribute. – chepner Jun 17 '20 at 12:39
  • That's right I will remove it from the answer, Tnx for that – Leo Arad Jun 17 '20 at 12:40