Is it better to use self variable than pass variable in a class?

python

Solution

In Python, you have a lot of freedom to do what "makes sense". In this case, I would say that it depends on how you plan on using `func2` and who will be accessing it. If `func2` is only ever supposed to act upon `self.var`, then you should code it as such. If other objects are going to need to pass in different arguments to `func2`, then you should allow for it to be an argument. Of course, this all depends on the larger scope of what you're trying to do, but given your simple example, this makes sense.

Also, I'm confused about how your question relates to global variables. Member variables are not the same thing as global variables.

Edited to reflect updated post:

The difference between A and B in your example is that B persists the information about `self.var`, while A does not. If `var` needs to be persisted as part of the object's state, then you need to store it as part of `self`. I get the sense that your question might relate more to objects as a general concept than anything Python-specific.

Problem

I used to be a c programmer, so we have to pass every variable as argument or pointer and not encouraged to define global variable. I am going to use some variable in several functions in python. Generally, which is better, pass the variable as an argument, or define a self variable when we get the value of the variables? Does python has any general rules about this? Like this: ``` class A: def func2(self, var): print var def func1(self): var = 1 self.func2(var) class B: def func2(self): print self.var def func1(self): self.var = 1 self.func2() ``` Which is better? A or B?

Original source