码迷,mamicode.com
首页 > 编程语言 > 详细

python中非序列类型期望值拷贝的解决方案

时间:2014-06-29 21:38:46      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:解决方案   python   return   

看下面这段代码:


# -*- coding: utf-8 -*-
import copy

class Present(object):
    def __init__(self, str_cmd):
        self._str_cmd = str_cmd
        print "进入Present时的地址:", id(self._str_cmd)

    def set_value(self):
        temp = "test_cmd"
        self._str_cmd = copy.deepcopy(temp)

    def get_value(self):
        return self._str_cmd

    def print_value(self):
        # print self._str_cmd
        print "在Present中被赋值后的地址:", id(self._str_cmd)

class Son(Present):
    def __init__(self, str_cmd):
        Present.__init__(self, str_cmd)

        self.str_cmd = str_cmd

    def Son_print(self):
        print "Son中的当前地址: ", id(self.str_cmd)
        self.str_cmd = self.get_value()
        print "Son中get_value之后的地址", id(self.str_cmd)

if __name__ == "__main__":
    str_cmd = "first"
    print "最开始的地址: ", id(str_cmd)
    test = Son(str_cmd)
    test.set_value()
    test.print_value()
    test.Son_print()

# -*- coding: utf-8 -*-
import copy

class Present(object):
    def __init__(self, str_cmd):
        self._str_cmd = str_cmd
        print "进入Present时的地址:", id(self._str_cmd)

    def set_value(self):
        temp = "test_cmd"
        self._str_cmd = copy.deepcopy(temp)

    def get_value(self):
        return self._str_cmd

    def print_value(self):
        # print self._str_cmd
        print "在Present中被赋值后的地址:", id(self._str_cmd)

class Son(Present):
    def __init__(self, str_cmd):
        Present.__init__(self, str_cmd)

        self.str_cmd = str_cmd

    def Son_print(self):
        print "Son中的当前地址: ", id(self.str_cmd)
        <span style="color:#ff0000;">self.str_cmd = self.get_value()</span>
        print "Son中get_value之后的地址", id(self.str_cmd)

if __name__ == "__main__":
    str_cmd = "first"
    print "最开始的地址: ", id(str_cmd)
    test = Son(str_cmd)
    test.set_value()
    test.print_value()
    test.Son_print()


 

代码意图是Son中的str_cmd在Present中值被改变,但是在Son中希望能看到这个改变。如果没有标红的这行,那么程序执行结果如下:

 

最开始的地址:  39466208
进入Present时的地址: 39466208
在Present中被赋值后的地址: 39426752
Son中的当前地址:  39466208
Son中get_value之后的地址 39466208

 

在Son中看到的是39466208这个地址的内容,但是Present改变的是39426752,所以虽然名字一样,但实际两个类中看到的变量不是同一个。

如果加上红色的这句,那么结果变成:

 

最开始的地址:  39138528
进入Present时的地址: 39138528
在Present中被赋值后的地址: 39099072
Son中的当前地址:  39138528
Son中get_value之后的地址 39099072

 

这个时候get_value之后,Son和Present的str_cmd都已经指向了同一个Id,所以两者看到的已经是同一个变量。

用以上方案可以实现非序列变量的值拷贝,对于序列变量的值拷贝,直接使用copy.deepcopy即可。


python中非序列类型期望值拷贝的解决方案,布布扣,bubuko.com

python中非序列类型期望值拷贝的解决方案

标签:解决方案   python   return   

原文地址:http://lonestar.blog.51cto.com/9102001/1432002

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!