The Only Guide You'll Need For OOPS In Python

The Only Guide You'll Need For OOPS In Python

Object Oriented Programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that manipulates that data. 

OOP is a popular programming style in Python, and it has several benefits over other styles of programming, such as improved code organization and reuse, as well as better support for complex and large-scale projects.

In Python, an object is a piece of data that is encapsulated within a class. 

A class is a template or blueprint for creating objects, and it defines the attributes and behaviors that objects of that class will have. 

For example, consider the following class definition for a simple "Person" class:




class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def say_hello(self):
print("Hello, my name is " + self.name + " and I am " + str(self.age) + " years old.")



The Person class has two attributes: name and age, and it has a single behavior, which is the say_hello method. 

The __init__ method is a special method in Python that is used to initialize an object when it is created. It is called a constructor, and it takes two arguments: name and age, which are used to set the values of the name and age attributes for the object. 

To create an object of the Person class, you use the class_name() syntax, like so:




p = Person("Alice", 25)


This creates a new object of the Person class and assigns it to the p variable. 

To access the attributes of an object, you use the dot notation, like so:




print(p.name) # prints "Alice"
print(p.age)

Output


"Alice"
25


To call a method of an object, you use the same syntax, like so:




p.say_hello()

Output


Hello, my name is Alice and I am 25 years old.


One of the main benefits of OOP is that it allows you to create classes that can be inherited by other classes. 

This means that you can create a base class with certain attributes and behaviors, and then create other classes that inherit from that base class and add their own attributes and behaviors. For example:




class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id

def enroll(self):
print("Enrolling student with ID " + self.student_id)

s = Student("Bob", 20, "123456")
print(s.name)
print(s.age)
print(s.student_id)
s.enroll()

Output


"Bob"
20
"123456"
"Enrolling student with ID 123456"


In the example above, we create a Student class that inherits from the Person class. 

The Student class has an additional attribute called student_id, and it has a new behavior called enroll. 

The Student class also has its own __init__ method, which helps in initializing the student object.