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


看下面这段代码:

# -*- 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)

代码意图是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核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

相关内容

    暂无相关文章