Python Object Oriented Programming

Python Object Oriented Programming

Object oriented programming is one of the programming approaches in solving the problems with programming. Python supports object oriented programming(OOP) approach. While using OOPS in python we mostly use terms like object, class, method, etc.

Some of the principles of Object Oriented Programming

  • class
  • object
  • method
  • inheritance
  • polymorphism
  • data abstraction
  • encapsulation

class

  • Class is a program-code-template for creating the objects.
  • Classes provide a means of bundling data and functionality together.
  • Class Definition Syntax

    class ClassName:
    <statement-1>
    .
    .
    .
    <statement-n>
    
  • example class

    class MyClass:
    """A simple example class"""
    i = 12345
    
    def f(self):
        return 'hello world'
    

object

  • object refers to a particular instance of a class, where the object can be a combination of variables, functions, and data structures.
  • object can have state and behaviour.
  • creation of object is called instantiation, hence object is called as instance of the class.
  • let's create the object for above class.

    x = MyClass()
    print("Value of attribute i:", x.i)
    # Output: 12345
    

method

  • method is a function/procedure that is associated with the object.
  • let's see an example

    x = MyClass()
    print("Value of method f():", x.f())
    # Output: hello world
    

inheritance

  • Inheritance is simply aquiring the properties from the parent class to the inherited class.
  • Let's consider that we have two classes "A" and "B". If class "B" inherits the class "A" then class "A" is called as Base Class / Super Class for class "B".
  • Class "B" is called as child class for class "A".

polymorphism

  • Polymorphism is the ability to leverage the same interface for different underlying forms such as data types or classes. This permits functions to use entities of different types at different times. Reference:

https://docs.python.org/3/tutorial/classes.html