0

我试图让我的小脚本工作,但我不知道问题是什么,其中一种方法会修改我的测试变量,即使我不返回它,我的意思是,我想在本地使用它而不是返回值。这不是我的实际代码,但您可以确定代表它。

更新:我正在使用字典

    >>> class check:
    ...   def pathgen(self,test):
    ...     test['a']=0
    ...     print test
    ...   def assign(self):
    ...     test={'a':1}
    ...     self.pathgen(test)
    ...     print test #WILL PRINT 0
    ... 
    >>> a=check()
    >>> a.assign()
    {'a': 0}
    {'a': 0}
4

3 回答 3

3

您正在使用函数本地名称。在实例上设置属性(通过self)以在方法之间共享信息:

class check:
     def pathgen(self):
         self.test = 0
         print self.test
     def assign(self):
         self.test = 1
         self.pathgen()
         print self.test
于 2013-03-13T18:10:18.807 回答
1

在您的代码中,'pathgen' 将修改其第一个参数指向的任何内容。为避免这种情况,您可以在对其进行任何更改之前复制“测试”

有关此处复制的更多信息:http: //docs.python.org/2/library/copy.html

class check:
    def pathgen(self,test):
        local_copy = test.copy()
        local_copy['a'] = 0
        print local_copy
于 2013-03-13T19:04:28.347 回答
0

你的假设是错误的。实际上,该WILL PRINT 0行将打印1.

test请注意,如果是一个列表,情况会有所不同,并且pathgen要对其进行修改(例如,通过附加一个元素):

class check:
     def pathgen(self,test):
         test.append(1)
         print test
     def assign(self):
         test=[]
         self.pathgen(test)
         print test

check().assign()

实际上,这将打印[1]两次。

这可以通过复制testin来解决pathgen

class check:
     def pathgen(self,test):
         test=test[:]    # make a shallow copy of `test'
         test.append(1)
         print test
     def assign(self):
         test=[]
         self.pathgen(test)
         print test

check().assign()
于 2013-03-13T18:10:08.213 回答