开发者

Could someone help me here? Python object maintaining between separate functions

I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem.

import copy

class Obj(object):
    def __init__(self, name):
        self.name = name

def one(o):
    print("1: o.name:", o.name) # "foo"
    obackup = copy.deepcopy(o)开发者_C百科 
    o.name = "bar"
    print("2: o.name:", o.name) # "bar"
    print("3: obackup.name:", obackup.name) # "foo"
    o = obackup
    print("4: o.name:", o.name) # "foo"

def two(o):
    print("5: o.name:", o.name) # "bar"!

def main():
    o = Obj("foo")
    one(o)
    two(o)

main()

My guess is that o is being overwritten somehow as a local variable to the function one(). But I have no idea how to fix that.


Forget that the copy module exists, it almost never is needed and often produces surprising results.

As soon as you say o = obackup in one() you have created a new binding for the formal argument which then goes out of scope after print('4...


o is a local variable to the one() so this problem cannot be fixed elegantly. But you could use some reference/pointer which you pass to the one() and two().

Simulating Pointers in Python

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜