
👉Python OOPs Concepts
Python’s Object-Oriented Programming (OOPs) concept is a powerful paradigm that emphasizes the use of classes and objects. This approach is widely used to build scalable and reusable code structures. Let’s explore Python OOPs concepts in detail with practical examples.
👉What is a Class in Python?
Python OOPs Concepts: A class in Python is a blueprint for creating objects. It groups data (attributes) and functions (methods) that operate on that data.
👉Example:
python
class MyClass:
def method1(self):
print(“Hello from method1”)
def method2(self, someString):
print(“Message:”, someString)
👉Key Points about Classes in Python:
- Defining a Class: Use the class keyword followed by the class name.
- Methods Inside a Class: Define methods using def keyword; the first parameter is always self.
- Creating Objects: Instantiate the class using object_name = ClassName()
- Calling Methods: Use object_name.method_name()
👉Example Code:
python
class MyClass:
def method1(self):
print(“Software Moji Moji”)
def method2(self, someString):
print(“Software Testing:”, someString)
def main():
obj = MyClass()
obj.method1()
obj.method2(“Python OOPs is fun”)
if __name__ == “__main__”:
main()
👉Python Inheritance
Inheritance allows a new class (child class) to inherit properties and methods from an existing class (parent class). This enables code reusability and simplifies code management.
👉Syntax for Inheritance:
python
class ParentClass:
# Parent class methods
class ChildClass(ParentClass):
# Child class methods
👉Example of Inheritance in Python:
python
class ParentClass:
def method1(self):
print(“This is method1 from ParentClass”)
class ChildClass(ParentClass):
def method2(self):
print(“This is method2 from ChildClass”)
# Creating object for child class
obj = ChildClass()
obj.method1() # Calls method from ParentClass
obj.method2() # Calls method from ChildClass
In this example:
- The ChildClass inherits method1() from the ParentClass.
- The ChildClass has its own method2().
👉Python Constructor
A constructor is a special method in Python used for initializing objects. The constructor method is defined using __init__() and is automatically called when an object is created.
👉Example of Constructor in Python:
python
class User:
def __init__(self, name):
self.name = name
def greet(self):
print(“Welcome to Software Moji Moji,”, self.name)
# Creating an object
user1 = User(“Alex”)
user1.greet()
👉Output:
css
Welcome to Software Moji Moji, Alex
👉Summary of Python OOPs Concepts:
✅ Class: A blueprint for creating objects.
✅ Object: An instance of a class.
✅ Inheritance: Enables a child class to inherit methods from a parent class.
✅ Constructor (__init__): Initializes an object automatically when created.
✅ Self: Refers to the instance of the class.