When I write class in python, most of the time, I am eager to set variables I use, as properties of the object. Is there any rule or general guidelines about which variables should be used as class/instance attribute and which should not?
for example:
class simple(object):
def __init(self):
a=2
b=3
return a*b
class simple(object):
def __init(self):
self.a=2
self.b=3
return a*b
While I completely understand the attributes should be a property of the object. This is simple to understand when the class declaration is simple but as the program goes longer and longer and there are many places where the data exchange between various modules should be done, I get confused on where I should use a/b or self.a/self.b. Is there any guidelines for this?
Where you use
self.ayou are creating a property, so this can be accessed from outside the class and persists beyond that function. These should be used for storing data about the object.Where you use
ait is a local variable, and only lasts while in the scope of that function, so should be used where you are only using it within the function (as in this case).Note that
__initis misleading, as it looks like__init__– but isn’t the constructor. If you intended them to be the constructor, then it makes no sense to return a value (as the new object is what is returned).