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?