How does this python script work?

I've been messing around with python and I've come across something I can't quite wrap my head around. I have the following code:

class test1:

    def __init__(self):
        self.__name = "Test"

    def getName(self):
        return self.__name

    def setName(self, name):
        self.__name = name

class test2:
    def __init__(self):
        self.__test1 = test1()

    def getTest1(self):
        return self.__test1

    def setTest1Name(self, name):
        test = self.getTest1()
        test.setName(name)

var = test2()
var.setTest1Name("This works...")

print var.getTest1().getName() #returns "This works" rather than "Test"

What confuses me here is that the setTest1Name() method actually changes the "__name" field of the test2 instance's "__test1" field. What I would expect is that the test = self.getTest1() line would create a new test1 instance bound to the name "test" which would be a copy of the test2 instance's "__test1" field. Then the test.setName(name) line would change the "__name" field of the new "test" variable but not the "__name" field of the test2 instance's "__test1" field.

In short: Why does this script print "This works..." rather than "Test"?

Also... Is it bad practice to take advantage of this? If so what might be a better option?

(I apologize for the vague title. I have no idea what to title the question.)

Answers


Plain assignment does not copy anything in Python. test = self.getTest1() does not set test to a copy of self.__test1; it sets test to the same object as self.__test1. Google and search this site for literally thousands of other questions and discussions about this.


The function getTest1(self) doesn't create a new instance, it only return the existing one.


Need Your Help

Recursive XSL Selection

xml xslt recursion

The XML looks like this: