开发者

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

开发者 https://www.devze.com 2023-01-13 01:40 出处:网络
I wrote this simple python program to help me with a bug in another program. It clearly illustrates the problem.

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

精彩评论

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