Understanding Python OOPS Concepts
What is OOPS Concept in Python?
Python can be used in several ways and supports a variety of programming methods.
Creating objects is a common way to address a programming challenge. Object-Oriented Programming is the term for this (OOP). Here, let’s go through Python Object-Oriented Programming and important concepts related to it.
An object has two characteristics:
1. attributes
2. behavior
Let's take an example:
A Penguin is an object because it possesses the following characteristics:
name, age, color as attributes
singing, dancing as behavior
The notion of OOPS in Python focuses on writing reusable code. DRY (Don't Repeat Yourself) is another name for this principle.
Understanding Class in Python OOPS
A class is an object's blueprint. The class can be compared to a sketch of a Penguin with labels. It provides all of the information regarding the name, colors, and size, among other things.
We can learn more about the Penguin by studying these descriptions. A Penguin is an object in this case.
An example for the class of Penguin can be:
class Penguin:
pass
The class keyword is used to create an empty class called Penguin. We create instances from classes. A unique object formed from a certain class is referred to as an instance.
What is Object in Python OOPS?
A class is instantiated as an object (instance). Only the object's description is defined when class is defined. As a result, no memory or storage is assigned.
An example of the object of the Penguin class can be:
obj = Penguin()
Here, obj is an object of class Penguin.
Assume we have information on Penguins. Now we'll teach you how to create the Penguin class and objects.
class Penguin:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Penguin class
pigeon= Penguin("Pigeon", 10)
parrot= Penguin("Parrot", 15)
# accessing class attributes
print("Pigeon is a {}".format(pigeon.__class__.species))
print("Parrot is also a {}".format(parrot.__class__.species))
# accessing instance attributes
print("{} is {} years old".format( pigeon.name, pigeon.age))
print("{} is {} years old".format( parrot.name, parrot.age))
Output: