Note that there are some explanatory texts on larger screens.

plurals
  1. POconfusion about class instances
    primarykey
    data
    text
    <p>I create several instances of my class in a loop and expect those to be independent. But to my confusion, when I create a new instance with the same name, it keeps properties of the instance created before.</p> <p>So I have something like:</p> <pre><code>class myClass(object): def __init__(self, i1 = None, i2 = 'X', p1 = [], p2 = []): self.i1, self.i2 = i1,i2 self.property1 = p1 self.property2 = p2 def doStuff(self): self.property1.append(self.i1) self.property2.append(self.i2) print self.property1 print self.property2 class mySubClass(myClass): def __init__(self, i1 = None, i2 = 'Z'): myClass.__init__(self, i1, i2) inputTuples = (('A', 'B'), ('D', 'E')) for x,y in inputTuples: o=mySubClass(x) pprint(vars(o)) o.doStuff() print(id(o)) {'i1': 'A', 'i2': 'Z', 'property1': [], 'property2': []} ['A'] ['Z'] 37087832 {'i1': 'D', 'i2': 'Z', 'property1': ['A'], 'property2': ['Z']} ['A', 'D'] ['Z', 'Z'] 37088392 </code></pre> <p>So for the 1st time it loops, pprint shows o.property1 =[] For the second time, it shows o.property1 is a list of whatever got appended to o in the first run of the loop.</p> <p>My understanding was that when I call o=myClass(), a new instance of that class would be created and the old one will be deleted (effectively overwrtitten)</p> <p>Could anyone explain to me how python works here and how I could make it work the way I want?</p> <p>If I change the class to</p> <pre><code>class myClass(object): def __init__(self, i1 = None, i2 = 'X': self.i1, self.i2 = i1,i2 self.property1 = [] self.property2 = [] </code></pre> <p>it works fine</p> <pre><code>{'i1': 'A', 'i2': 'Z', 'property1': [], 'property2': []} ['A'] ['Z'] 37087832 {'i1': 'D', 'i2': 'Z', 'property1': [], 'property2': []} ['D'] ['Z'] 37088392 </code></pre> <p>I dont understand the fundamental difference here. Also, how can I keep the possibility of having p1 and p2 as input variables and still ahve the desired behaviour?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload