Python OOPs Concepts

Python OOPs Concepts

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.

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.

Example of Class and Objects

In this example, we have two objects Ram and Steve that belong to the class Human
Object attributes: name, height, weight
Object behaviour: eating()
Also read: How to create class and objects in Python.

Source code

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"))
Output:
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

No comments:

Post a Comment

Your feedback is highly appreciated and will help us to improve our content.