# point.py # CS 313 - simple example for object-oriented programming in Python ### simplest possible way: define an empty class class Point1: pass # like {} in Java p = Point1() p.x = 3 p.y = 5 print p.x, p.y ### slightly fancier: provide methods that access instance variables # note: all methods need 'self' as first parameter class Point2: def setxy(self, x, myy): self.x = x self.y = myy # note: need "self." (can't skip like "this." in Java) def getx(self): return self.x def gety(self): return self.y p = Point2() p.setxy(4, 6) # WHAT HAPPENS: within the class, calls setxy(p, 4, 6) print p.getx(), p.gety() print p.x, p.y # this is still legal # even fancier: provide "constructor" __init()__ # also demonstrates parameters with default values and inheritance class Point3(Point2): # SUBCLASS of Point2 def __init__(self, x=0, y=0): # default values for parameters self.x = x self.y = y p = Point3(2, 2) # calls __init__ print p.x, p.y print p.getx(), p.gety() # inherited from Point2 q = Point3(10) # only provide value for x, use default for y print q.x, q.y