Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Basic Python Object

$
0
0

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:

# 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 [49] (39,49)

As always, I hope that helps those looking for a solution.


Viewing all articles
Browse latest Browse all 9596

Trending Articles