Object Oriented Programming¶
A programming paradigm that uses ‘Classes’ and interactions between ‘Objects’ to design applications and computer programs.
A class can be considered a template or blueprint that can be used to create objects.
- An object is a specific instance of a class.
- Using the class (template), objects from the class can be created.
- Each object has its own copy of the state (defined by properties) defined in the class.
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
- 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
Ready for some practice? Test your understanding at Pyschools: Classes and Objects.