Posted by Kosal
Object-oriented programming (OOP) in Python involves creating classes and objects to model real-world entities and their interactions. Here's a step-by-step guide on how to use OOP in Python:
Define a Class:
Start by defining a class using the class
keyword. This defines a blueprint for creating objects.
class MyClass:
# Class attributes and methods go here
pass
Add Attributes and Methods: Define attributes (variables) and methods (functions) inside the class. These attributes and methods define the behavior and properties of the objects created from the class.
class MyClass:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def my_method(self):
return self.attribute1 + self.attribute2
Instantiate Objects: Create objects (instances) of the class using the class name followed by parentheses.
obj1 = MyClass(5, 10)
obj2 = MyClass(3, 7)
Access Attributes and Call Methods:
You can access the attributes and call methods of an object using the dot notation (obj.attribute
or obj.method()
).
print(obj1.attribute1) # Output: 5
print(obj2.my_method()) # Output: 10
Inheritance: Inheritance allows a class to inherit attributes and methods from another class. This enables code reusability and facilitates creating subclasses with additional features.
class MySubClass(MyClass):
def __init__(self, attribute1, attribute2, attribute3):
super().__init__(attribute1, attribute2)
self.attribute3 = attribute3
def my_sub_method(self):
return self.attribute1 * self.attribute3
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common superclass. This is often achieved through method overriding.
class MySubClass(MyClass):
def my_method(self):
return self.attribute1 * self.attribute2
Encapsulation:
Encapsulation involves restricting access to certain parts of an object to prevent unintended interference. In Python, this is typically achieved by using private variables (attributes and methods) indicated by a leading underscore _
.
class MyClass:
def __init__(self, attribute1, attribute2):
self._attribute1 = attribute1
self._attribute2 = attribute2
def _my_private_method(self):
pass
These are the fundamental concepts of object-oriented programming in Python. Practice and experimentation will help you become proficient in utilizing OOP principles effectively in your projects.