[英]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. 我一直在搞弄python,遇到了一些我无法完全解决的问题。 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. 让我感到困惑的是,setTest1Name()方法实际上更改了test2实例的“ __test1”字段的“ __name”字段。 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. 我期望的是
test = self.getTest1()
行将创建一个绑定到名称“ test”的新test1实例,该实例将是test2实例的“ __test1”字段的副本。 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. 然后,
test.setName(name)
行将更改新“ test”变量的“ __name”字段,但不会更改test2实例的“ __test1”字段的“ __name”字段。
In short: Why does this script print "This works..." rather than "Test"? 简而言之:为什么此脚本打印“ This works ...”而不是“ 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. 普通分配不会在Python中复制任何内容。
test = self.getTest1()
does not set test
to a copy of self.__test1
; test = self.getTest1()
不会将test
设置为self.__test1
的副本; it sets test
to the same object as self.__test1
. 它将
test
设置为与self.__test1
相同的对象。 Google and search this site for literally thousands of other questions and discussions about this. Google并在此站点上搜索有关此问题的数千个其他问题和讨论。
函数getTest1(self)不会创建新实例,它只会返回现有实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.