设为首页 加入收藏

TOP

Python中非序列类型期望值拷贝的解决方案
2014-11-23 22:10:11 来源: 作者: 【 】 浏览:26
Tags: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即可。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇AngularJS 的 IE 兼容性 下一篇在终端中运行 Swift 程序

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: