0

i'm newer in python but i have some package from other languages . Here's my question : i need to change an instance reference inside a function.This instance is passed as parameter. but i didn't know how to do it. I think i miss something in Python basics.The code bellow is given as example for what i want:

class Foo(object): 
   def __init__(self,a):
      self.a = a


def func(a):
   b = Foo(3)
   a = b

var1 = Foo(5)
print(var1.a) # 5
func(var1)
print(var1.a) # it display 5 not 3
1
  • 1
    You mean you want a copy of the object? Commented Mar 26, 2014 at 13:56

2 Answers 2

1

You can make func return a and then assign that to var1 as follows:

def func(a):
   b = Foo(3)
   a = b
   return a

var1 = Foo(5)
print(var1.a) # 5
var1 = func(var1)
print(var1.a) # 3

>>> var1.a
3

What you were doing in your code is that you were changing the pointer for the local variable a in your func(a) method. However, if you want to change the var1 pointer, you have to assign the changed a variable that you passed as an argument.

Sign up to request clarification or add additional context in comments.

1 Comment

first,thank you for reply. But it's not what i want.may be because i didn't mention that the function shouldn't return. it's an implementation that i should respect.
0

One way is to use an umutable object such as the list and the property functions that automagically does what you need.

class Foo(object): 
    def __init__(self, value):
        self._a = [value]

    def __geta(self):
        return self._a[0]

    def __seta(self, obj):
        self._a.insert(0, obj)
        self._a.pop(1)

    a = property(__geta, __seta)

var1 = Foo(5)
print var1.a
var1.a = 3
print(var1.a)

1 Comment

i thought to do such at first, but it still doesn't work. the probleme is when you back from the function the object is the same.(the modication should be inside a function)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.