I am writing a large amount of code and I haven’t got enough experience on the best way of using variables in a python class and its functions so I thought I would ask for some opinions. Here is an example of how I could do it
class MyClass():
vara = 'Class Variable A'
def __init__(self):
self.varb = 'Class instantiation Variable B'
def a(self):
varc = 2
vard = 3
print 'def a function variables unchanged', varc, vard
MyClass.vara = 'Class Variable A now changed by def a'
def b(self):
print self.varb
self.varb = 'Class instantiation Variable B now changed by def b'
print self.varb
if __name__ == "__main__":
print MyClass.vara
a = MyClass()
a.a()
a.b()
print MyClass.vara
a.a()
This gives this result
Class Variable A
def a function variables unchanged 2 3
Class instantiation Variable B
Class instantiation Variable B now changed by def b
Class Variable A now changed by def a
def a function variables unchanged 2 3
My app in django is using a class with has around 25 functions. Its a test application and each function represents an API call. Each API call will give out a few variables based on the result and I need these variables set by the functions to be used by other functions – so in other words I need to call these local function variables by other functions. I want to know the best way to do this.
In the example above, I can set the class variable vara using a function within the class, by doing this MyClass.vara = 'something' or I can set the variable which is in the instantiation constructor, __init__. Then I can call these variables using any function.
What’s the better way, or is there an even better way to do this?
Not sure if I fully get what you’re asking, but if I understand you correctly, the answer is that it depends what you want to do. You should set the attribute on the class (as in your
vara) if you want it to be stored once for the entire class. You should set it on the instance in__init__(as in yourvarb) if you want a separate attribute for each instance.The difference becomes clearer if you have a mutable object (like a list) as the value of the attribute. See below:
Notice that in the last bit, mutating
f.classVaralso affectedg.classVar. Because this is a class attribute, it is shared among all instances of the class. The instance attribute (instVar) is independent for each instance.