Possible Duplicate:
Python: How do I pass a variable by reference?
I have the following case:
class A:
def __init__(self):
self.test = ''
self.func(self.test)
print(self.test)
def func(self,var):
var = 'foo'
I want func to modify self.var and I’d like to be able to pass a self. to this method.
A bit like:
class A()
{
public:
char test[256];
A() { func(test);}
private:
void func(char * var) { var = "foo"; }
};
I haven’t written C++ in a while but that’s sort of what I’m going for.
Unfortunately, I don’t know
C++very well, but I’m guessing you want something like this:We have to do it this way because we can change (mutate)
self.testinside 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: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 onself. Given those two pieces of information, we can make the desired changes — Of course, at this point, you’re probably best off getting rid offuncall together and just usingsetattrdirectly.It’s probably also worth asking why you actually want to do this. In general, you can just do:
why would you want to write:
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).