PySchools Python Quick Reference Guide

Object Oriented Programming

«  Tuples   ::   Contents   ::   Recursions  »

Object Oriented Programming

Python and OOP

Python is an Object Oriented Programming Language. To create a class, use the following format:

class FourSidedShape:                   # specify the name of the class

    def __init__(self, len, wid):       # constructor of the class, take note of the double underscore on both side
        self.legnth = len               # instance variable
        self.width = wid

    def calculate_area(self):           # a method, need to include self as first argument
        return self.length * self.width

    def print_area(self):
        print "The area of the shape is " + str(self.calculate_area())

To create an object instance:

>>> myShape = FourSidedShape(4, 3)      # Create an object
>>> myShape.calculate_area()            # Invoke the calculate_area() method, take note that no argument is passed in to the method
12
>>> myShape.print_area()
'The area of the shape is 12'
>>> myShape.length                      # Access the instance variable
4

Inheritance

  • Object-oriented programming allows classes to?inherit?commonly used state and behaviour from other classes.
  • Reduce code duplication

Example of Inheritance:

class Square(FourSidedShape):                       # Inherited class enclosed in bracket
    def __init__(self, side):
        FourSidedShape.__init__(self, side, side)   # Call the parent class constructor

    def calculate_area(self):
        return FourSidedShape.calculate_area(self)  # Call the parent class method

    def print_area(self):
        print "The area of the square is " + str(self.calculate_area()) # over-ride the parent class method

See also

Ready for some practice? Test your understanding at Pyschools: Classes and Objects.

«  Tuples   ::   Contents   ::   Recursions  »