I was wondering how should one access the instance variables in a python class. Should i make a method for every instance variable or should i access them directly?
Here’s an example:
class Example(object):
def __init__(self):
self.x = 5
def getX(self):
return self.x
def addYtoX(self, y):
return self.x + y # OR: return self.getX() + y
Thank you!
Mostly, just access them directly. Python is not Java.
In Java, you have to use getters and setters because you cannot change your mind and change the public fields to getters and setters later on. In python, you can, so don’t use getters and setters until you have an actual need to. Then you switch to a
propertyinstead.