Updated On : May-13,2020 Time Investment : ~15 mins

Python Programming Guide For Beginners - Part 7

Learning Python OOPs Concepts

Table Of Content

  1. What Is The Python OOP Concept?
  2. How to create 'Class' and 'Objects' in Python
  3. Creating Objects of class
  4. Example of Class and Objects
  5. Python Constructors – default and parameterized
  6. Types of constructors in Python
  7. What is a constructor?
  8. Python – default constructor example

What Is The Python OOP Concept?

Python is an object-oriented programming language. What this means is we can solve a problem in Python by creating objects in our programs. In this guide, we will discuss OOPs terms such as class, objects, methods etc. along with the Object oriented programming features such as inheritance, polymorphism, abstraction, encapsulation.

Undertsanding The Basic Terms:

Object An object is an entity that has attributes and behaviour. For example, Ram is an object who has attributes such as height, weight, color etc. and has certain behaviours such as walking, talking, eating etc.

Class A class is a blueprint for the objects. For example, Ram, Shyam, Steve, Rick are all objects so we can define a template (blueprint) class Human for these objects. The class can define the common attributes and behaviours of all the objects.

Methods As we discussed above, an object has attributes and behaviours. These behaviours are called methods in programming.

How to create 'Class' and 'Objects' in Python

To define class in Python you need to use a class is defined using the keyword class.

Example In this example, we are creating an empty class DemoClass. This class has no attributes and methods.

The string that we mention in the triple quotes is a docstring which is an optional string that briefly explains the purpose of the class.

class DemoClass:
    """This is my docstring, this explains brief about the class"""

# this prints the docstring of the class
print(DemoClass.__doc__)
This is my docstring, this explains brief about the class

Creating Objects of class

In this example, we have a class MyNewClass that has an attribute num and a function hello(). We are creating an object obj of the class and accessing the attribute value of object and calling the method hello() using the object.

class MyNewClass:
    """This class demonstrates the creation of objects"""

    # instance attribute
    num = 100

    # instance method
    def hello(self):
        print("Hello World!")
# creating object of MyNewClass
obj = MyNewClass()

# prints attribute value
print(obj.num)

# calling method hello()
obj.hello()

# prints docstring
print(MyNewClass.__doc__)
100
Hello World!
This class demonstrates the creation of objects

Example of Class and Objects

  • Object attributes: name, height, weight
  • Object behaviour: eating()
class Human:
    # instance attributes
    def __init__(self, name, height, weight):
        self.name = name
        self.height = height
        self.weight = weight

    # instance methods (behaviours)
    def eating(self, food):
        return "{} is eating {}".format(self.name, food)


# creating objects of class Human
ram = Human("Ram", 6, 60)
steve = Human("Steve", 5.9, 56)

# accessing object information
print("Height of {} is {}".format(ram.name, ram.height))
print("Weight of {} is {}".format(ram.name, ram.weight))
print(ram.eating("Pizza"))
print("Weight of {} is {}".format(steve.name, steve.height))
print("Weight of {} is {}".format(steve.name, steve.weight))
print(steve.eating("Big Kahuna Burger"))
Height of Ram is 6
Weight of Ram is 60
Ram is eating Pizza
Weight of Steve is 5.9
Weight of Steve is 56
Steve is eating Big Kahuna Burger

Python Constructors – default and parameterized

Definition:

A constructor is a special kind of method which is used for initializing the instance variables during object creation. In this guide, we will see what is a constructor, types of it and how to use them in the python programming with examples.

Types of constructors in Python

We have two types of constructors in Python.

  1. default constructor – this is the one, which we have seen in the above example. This constructor doesn’t accept any arguments.
  2. parameterized constructor – constructor with parameters is known as parameterized constructor.

1. What is a Constructor in Python?

Constructor is used for initializing the instance members when we create the object of a class.

Python – default constructor example

Note: An object cannot be created if we don’t have a constructor in our program. This is why when we do not declare a constructor in our program, python does it for us. Lets have a look at the example below.

def __init__(self):
    # no body, does nothing.
class DemoClass:
    # constructor
    def __init__(self):
        # initializing instance variable
        self.num=100

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class. This invokes constructor
obj = DemoClass()

# calling the instance method using the object obj
obj.read_number()
100

Syntax of constructor declaration

As we have seen in the above example that a constructor always has a name init and the name init is prefixed and suffixed with a double underscore(__).

We declare a constructor using def keyword, just like methods.

def __init__(self):
    # body of the constructor

Python – Parameterized constructor example

When we declare a constructor in such a way that it accepts the arguments during object creation then such type of constructors are known as Parameterized constructors. As you can see that with such type of constructors we can pass the values (data) during object creation, which is used by the constructor to initialize the instance members of that object.

class DemoClass:
    num = 101

    # parameterized constructor
    def __init__(self, data):
        self.num = data

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class
# this will invoke parameterized constructor
obj = DemoClass(55)

# calling the instance method using the object obj
obj.read_number()

# creating another object of the class
obj2 = DemoClass(66)

# calling the instance method using the object obj
obj2.read_number()
55
66

Method1 : When we do not declare a constructor

class DemoClass:
    num = 101

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class
obj = DemoClass()

# calling the instance method using the object obj
obj.read_number()
101

Method2: When we declare a constructor

class DemoClass:
    num = 101

    # non-parameterized constructor
    def __init__(self):
        self.num = 999

    # a method
    def read_number(self):
        print(self.num)


# creating object of the class
obj = DemoClass()

# calling the instance method using the object obj
obj.read_number()
999
Dolly Solanki  Dolly Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription