1

I am new to python, and more used to C++. I want to create a list of instances and did the following:

from copy import deepcopy

class C:
    c1=""
    c2=""

Cs=[]
C.c1="Hello"
C.c2="World"
Cs.append(deepcopy(C))

C.c1="Why"
C.c2="this?"
Cs.append(deepcopy(C))

for c in Cs:
    print (c.c1, c.c2)

I expected the following output:

Hello World
Why this?

but got:

Why this?
Why this?

Why is the deep copy not working?

PyNewbie
  • 31
  • 3
  • BTW, you aren't making any instances of that `C` class. Python classes work a little differently to C++. – PM 2Ring Oct 18 '17 at 06:37

1 Answers1

2

there is only one (static in the Java/C++ sense) copy of the c1 and c2 variables. Read https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide and sprinkle more selfs in your code to fix it.

mnagel
  • 6,729
  • 4
  • 31
  • 66
  • Thanks for pointing out this tutorial. I have changed my code to from copy import deepcopy class C: pass Cs=[] iC=C() iC.c1="Hello" iC.c2="World" Cs.append(deepcopy(iC)) iC.c1="Why" iC.c2="this?" Cs.append(deepcopy(iC)) for c in Cs: print (c.c1, c.c2)` Is this the preferred way of doing such a thing in python? – PyNewbie Oct 19 '17 at 05:10