PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) in Python

Updated on: March 18, 2021 | 3 Comments

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”. The object contains both data and code: Data in the form of properties (often known as attributes), and code, in the form of methods (actions object can perform).

In this lesson, you will learn about OOP (Object Oriented Programming) in Python. OOP concepts include object, classes, constructor and encapsulation, polymorphism, and inheritance.

Also See

  • Python OOP Exercise

An object-oriented paradigm is to design the program using classes and objects. Python programming language supports different programming approaches like functional programming, modular programming. One of the popular approaches is object-oriented programming (OOP) to solve a programming problem is by creating objects

Python OOP concepts
Python OOP concepts

Table of contents

  • Class
  • Object
  • Instance Variables and Methods
  • Constructors in Python
  • The self Parameter
  • Class Variable
  • Object Properties
    • Modify Object Properties
    • Delete object properties
  • Delete Objects
  • Encapsulation
  • Polymorphism
  • Inheritance
  • Next Steps

Class

In Python, everything is an object. A class is a blueprint for the object. To create an object we require a model or plan or blueprint which is nothing but class.

For example, developing a building according to the building plan. The plan contains all dimensions and structure. Based on these descriptions, we can construct a building. Here, a building is an object.

Class to represent the properties (attribute) and action (behavior) of the object. Properties represent variables, and actions are represented by the methods. Hence class contains both variables and methods.

Python Class and Objects
Python Class and Objects

Creating Class

In Python, create a class by using the keyword class. In the class definition, the first string is docstring which, is a brief description of the class.

The docstring is not mandatory but recommended to use. We can get docstring using __doc__ attribute. Use the following syntax to create a class.

Syntax

class classname:
    '''documentation string'''
   class_suiteCode language: Python (python)
  • Documentation string: represent a description of the class. It is optional.
  • class_suite: class suite contains component statements, variables, methods, functions, attributes.

Object

The physical existence of a class is nothing but an object. In other words, the object is an entity that has a state and behavior. It may be any real-world object like the mouse, keyboard, laptop, etc.

Creating object

We can create any number of objects for class. Below is the syntax used to create an object.

Syntax:

reference_variable = classname()Code language: Python (python)

Example: Creating Class and Object in Python

class Student:
    """This is student class with data"""

    # A sample method
    def learn(self):
        print("Learning Python Programming")

# creating object
stud = Student()
# Calling method
stud.learn()

# Output: Learning  Python ProgrammingCode language: Python (python)

In the above example, we created a Class with the name Student. Also, we created an object stud.

With help of class objects, we can access class methods. Here we accessing the learn() method by using the stud object.

Instance Variables and Methods

If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created.

When we create classes in Python, instance methods are used regularly. we need to create an object to execute the block of code or action defined in the instance method.

We can access the instance variable and methods using the object. Use dot (.) operator to access instance variables and methods.

In Python, working with an instance variable and method, we use the self keyword. When we use the self keyword as a parameter to a method or with a variable name is called the instance itself.

Note: Instance variables are used within the instance method

Example

class Student:
    def __init__(self, name, percentage):
        self.name = name
        self.percentage = percentage

    def show(self):
        print("Name is:", self.name, "and percentage is:", self.percentage)

stud = Student("Jessa", 80)
stud.show()

# Output Name is: Jessa and percentage is: 80Code language: Python (python)

In the above example, name and percentage are instance variables, and these variables get initialized when we create an object for the Student class. Here, the show() method is an instance method. If we want to call that method we need to create an object of the class.

instance variables and methods
instance variables and methods

Constructors in Python

In Python, a constructor is a special type of method used to initialize the object of a Class. The constructor will be executed automatically when the object is created. If we create three objects, the constructor is called three times and initialize each object.

The main purpose of the constructor is to declare and initialize instance variables. It can take at least one argument that is self. The __init()__ method is called the constructor in Python. In other words, the name of the constructor should be __init__(self).

A constructor is optional, and if we do not provide any constructor, then Python provides the default constructor. Every class in Python has a constructor, but it’s not required to define it.

We have two types of constructors in Python.

  1. Non-parameterized: The constructors in Python which have no parameter is known as a non parameterized constructor. The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument.
  2. Parameterized Constructor: The constructor with parameters is known as a parameterized constructor. The parameterized constructor has multiple parameters along with the self.

Example: Constructor without parameters (Non-parameterized)

class Test:
    # Constructor - non parameterized
    def __init__(self):
        print("This is non parametrized constructor")

    def show(self, name):
        print("Hello", name)

# creating object of the class
t = Test()
# Output:This is non parametrized constructor

# calling the instance method
t.show("Jessa")
# Output Hello JessaCode language: Python (python)

Example: Constructor with parameters

class Fruit:
    # parameterized constructor
    def __init__(self, name, color):
        print("This is parametrized constructor")
        self.name = name
        self.color = color

    def show(self):
        print("Fruit is", self.name, "and Color is", self.color)

# creating object of the class
# this will invoke parameterized constructor
obj = Fruit("Apple", "red")
# Output This is parametrized constructor

# calling the instance method using the object
obj.show()
# Output Fruit is Apple and Color is redCode language: Python (python)

In the above example, we create a parameterized constructor with parameters name and color. When we create an object of Test class called obj, the parameterized constructor will be executed automatically.

The self Parameter

The self is used to represent the instance of the class. It is the default variable that is always pointing to the current object.

By using self, we can access the instance variable and instance method of the object. While defining constructor and instance method, the self is their first parameter.

It’s not required the first parameter named to be self, we can give any name whatever we like, but it has to be the first parameter of any function in the class.

Example

class Employee:
    def __init__(self, id, name):
        # instance variable
        self.id = id
        self.name = name
    
    # instance method
    def info(self):
        print("Employee ID is ", self.id, "and name is", self.name)

    # instance method 
    def department(self):
        print("Employee of IT department")

emp = Employee(10112, "Harry", )
emp.info()
# Output Employee ID is 10112 and name is Harry

emp.department()
# Output Employee of IT departmentCode language: Python (python)

In the above example, all methods including __init__ have a self parameter. We created two instance variables id and name. Then we create an object of a class Employee called emp and accessed instance methods of the class called info() and department() respectively.

Class Variable

A class variable is a variable that is declared inside of class, but outside of any class method, they are not defined inside any class method.

Only one copy of the class variable will be created and shared by all objects of a class. Class variables are not used as frequently as instance variables.

A class variable alone looks like this:

class Student:
    # class Variable
    Subject = "Python"Code language: Python (python)

We can access class variables either by class name or object reference but recommended to use the class name.

Example

class Employee:
    depatment = "IT"

    def show(self):
        print("Department is ", self.depatment)

emp = Employee()
emp.show()
# Output Department is  IT

print("class variable:", Employee.depatment)
# Output ITCode language: Python (python)

In the above example, we declare a Class variable called the department. Also, we created an instance of Employee Class and print class variable using a class name with dot notation.

Object Properties

Every object has properties with it. In other words, we can say that object property is an association between name and value.

For example, a car is an object, and its properties are car color, sunroof, price, manufacture, model, engine, and so on. Here, color is the name and red is the value.

Object Properties
Object Properties

Modify Object Properties

Every object has properties associated with them. We can set or modify the object’s properties after object initialization by calling the property directly using the dot operator.

Obj.PROPERTY = valueCode language: Python (python)

Example

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def show(self):
        print("Fruit is", self.name, "and Color is", self.color)

# creating object of the class
obj = Fruit("Apple", "red")

# Modifying Object Properties
obj.name = "strawberry"

# calling the instance method using the object obj
obj.show()
# Output Fruit is strawberry and Color is redCode language: Python (python)

Delete object properties

We can delete the object property by using the del keyword. After deleting it, if we try to access it, we will get an error.

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def show(self):
        print("Fruit is", self.name, "and Color is", self.color)

# creating object of the class
obj = Fruit("Apple", "red")

# Deleting Object Properties
del obj.name

# Accessing object properties after deleting
print(obj.name)
# Output: AttributeError: 'Fruit' object has no attribute 'name'Code language: Python (python)

In the above example, As we can see, the attribute name has been deleted when we try to print or access that attribute gets an error message.

Delete Objects

In Python, we can also delete the object by using a del keyword. An object can be anything like, class object, list, tuple, set, etc.

Syntax

del object_nameCode language: Python (python)

Example : Deleteing object

class Employee:
    depatment = "IT"

    def show(self):
        print("Department is ", self.depatment)

emp = Employee()
emp.show()

# delete object
del emp

# Accessing after delete object
emp.show()
# Output : NameError: name 'emp' is not defined Code language: Python (python)

In the above example, we create the object emp of the class Employee. After that, using the del keyword, we deleted that object.

Encapsulation

In Python, encapsulation is a method of wrapping data and functions into a single entity. For example, A class encapsulates all the data ( methods and variables). Encapsulation means the internal representation of an object is generally hidden from outside of the object’s definition.

Python Encapsulation
Python Encapsulation

Need of Encapsulation

Encapsulation acts as a protective layer. We can restrict access to methods and variables from outside, and It can prevent the data from being modified by accidental or unauthorized modification. Encapsulation provides security by hiding the data from the outside world.

In Python, we do not have access modifiers directly, such as public, private, and protected. But we can achieve encapsulation by using single prefix underscore and double underscore to control access of variable and method within the Python program.

See the following example where we have implement encapsulation.

Example

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.__salary = salary

    def show(self):
        print("Name is ", self.name, "and salary is", self.__salary)

# Outside class
E = Employee("Jessa", 40000)
E.PrintName()
print(E.name)
print(E.PrintName())
print(E.__salary)
# AttributeError: 'Employee' object has no attribute '__salary'Code language: Python (python)

In the above example, we create a class called Employee. Within that class, we declare two variables name and __salary. We can observe that the name variable is accessible, but __salary is the private variable. We cannot access it from outside of class. If we try to access it, we will get an error

Polymorphism

Polymorphism is taken from the Greek words Poly (many) and morphism (forms). Polymorphism defines the ability to take different forms.

For example, The student can act as a student in college, act as a player on the ground, and as a daughter/brother in the home. Another example in the programming language, the + operator, acts as a concatenation and arithmetic addition.

Python Polymorphism
Python Polymorphism

In Python, polymorphism allows us to define the child class methods with the same name as defined in the parent class.

Example

class Circle:
    pi = 3.14

    def __init__(self, redius):
        self.radius = redius

    def calculate_area(self):
        print("Area of circle :", self.pi * self.radius * self.radius)

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        print("Area of Rectangle :", self.length * self.width)

cir = Circle(5)
rect = Rectangle(10, 5)
cir.calculate_area()
# Output Area of circle : 78.5

rect.calculate_area()
# Output Area od Rectangle : 50Code language: Python (python)

In the above example, we created two classes called Circle and Rectangle. In both classes, we created the same method with the name calculate_area. This method acts differently in both classes. In the case of the Circle class, it calculates the area of the circle, whereas, in the case of a Rectangle class, it calculates the area of a rectangle.

Inheritance

In an Object-oriented programming language, inheritance is an important aspect. The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class instead of creating it from scratch.

In Python, inheritance is the process of inheriting the properties of the parent class into a child class.

In inheritance, the child class acquires and access all the data members, properties, and functions from the parent class. Also, a child class can also provide its specific implementation to the functions of the parent class.

Use of inheritance

To create classes that are built upon existing classes called reusability. So, we do not have to write the same code again and again.

Syntax

class BaseClass:
  Body of base class
class DerivedClass(BaseClass):
  Body of derived classCode language: Python (python)

Example

class ClassOne:
    def func1(self):
        print('We are in Base class')

class ClassTwo(ClassOne):
    def func2(self):
        print('We are in child class')

obj = ClassTwo()
obj.func1()
obj.func2()Code language: Python (python)

Output:

We are in base class
We are in child class

In the above example, we create two classes called ClassOne and ClassTwo.The ClassTwo is derived from ClassOne that is the base class. While calling functions, create an object of child class called obj and called with the help of that object, that is, obj.func1.

Next Steps

  • Python OOP Exercise

Filed Under: Python

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Vikas says

    August 23, 2021 at 8:11 am

    Loved it, thank you for sharing 🙂

    Reply
  2. HermPY says

    June 16, 2021 at 7:12 am

    Outstanding work

    Reply
    • Vishal says

      June 20, 2021 at 9:17 am

      Thank you, Hermpy

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com