Unfortunately, I don't know C++
very well, but I'm guessing you want something like this:
class A:
def __init__(self):
self.test = ''
self.func("test")
print(self.test)
def func(self,var):
setattr(self,var,'foo')
We have to do it this way because we can change (mutate) self.test
inside a function (if it's mutable), but we can't change which object it references (which is what you're attempting to do with assignment). consider:
def func1(x):
x.append('foo')
def func2(x):
x = 'foo'
a = []
func1(a)
print a #['foo'] #mutated a in func1
func2(a)
print a #['foo'] #didn't change a in func2, only created a new local variable named `x` and assigned it to the string 'foo'
The only way around this is to pass some sort of proxy-like object which you can change. In this case, we pass the instance as the proxy object (self
) and the attribute's name (var
) so we know what to change on self
. Given those two pieces of information, we can make the desired changes -- Of course, at this point, you're probably best off getting rid of func
all together and just using setattr
directly.
It's probably also worth asking why you actually want to do this. In general, you can just do:
self.test = "foo"
why would you want to write:
self.func(self.test)
instead? I can understand if you're trying to do that since you're used to having private methods and attributes. But this is python. "We're all consenting adults here." Just rely on the conventions (prefix a variable with _
if you want to warn users against modifying it and prefix with __
to invoke name mangling to avoid collisions in superclasses).