0

I wrote the following python code.

I was expecting a new tmp instance in every loop, so every time I print tmp.c, I should get "[1]".

Why is this happening?

class f():
    c = []
    def __init__(self):
        self.c.append(1)

for i in range(5):
    tmp = f()
    print(tmp.c)
    print(tmp)

The output is:

<__main__.f object at 0x7f7566b0b7f0>
[1, 1]
<__main__.f object at 0x7f7566b0b668>
[1, 1, 1]
<__main__.f object at 0x7f7566b0b828>
[1, 1, 1, 1]
<__main__.f object at 0x7f7566b0b668>
[1, 1, 1, 1, 1]
<__main__.f object at 0x7f7566b0b828>
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

0

c is a static variable, it belongs to the class and to the the instance you can do id(c) and see the id is always the same

you want to do something like this

class f():
    def __init__(self):
        self.c = [1]

for i in range(5):
    tmp = f()
    print(tmp.c)
    print(tmp)
kill129
  • 100
  • 10