简体   繁体   中英

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.)

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.

函数getTest1(self)不会创建新实例,它只会返回现有实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM