One of my students wanted a quick example of a Python object with getters and setters. So, I wrote a little example that I’ll share.
You define this file in a physical directory that is in your $PYTHONPATH, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# Define Coordinate class. class Coordinate: # The method that initializes the Coordinate class. def __init__ (self, x, y): self.x = x self.y = y # Gets the x value from the instance. def getX (self): return self.x # Gets the y value from the instance. def getY (self): return self.y # Sets the x value in the instance. def setX (self, x): self.x = x # Sets the y value in the instance. def setY (self, y): self.y = y # Prints the coordinate pair. def printCoordinate(self): print (self.x, self.y)
Assuming the file name is Coordinate.py, you can put it into the Python Idle environment with the following command:
from Coordinate import Coordinate
You initialize the class, like this:
g = Coordinate(49,49)
Then, you can access the variables of the class or it’s methods as shown below:
# Print the retrieved value of x from the g instance of the Coordinate class. print g.getX() # Print the formatted and retrieved value of x from the g instance of the Coordinate class. print "[" + str(g.getX()) + "]" # Set the value of x inside the g instance of the Coordinate class. print g.setX(39) # Print the Coordinates as a set. g.printCoordinate()
You would see the following results:
49  (39,49)
As always, I hope that helps those looking for a solution.