Object-Oriented Programming (OOP) in Python is a programming paradigm that organizes code using "objects"-Instances of classes that encapsulate data (attributes) and behaviour (methods). OOP helps structure complex programs, making them easier to manage, extend, and maintain.
OOP concepts are needed because they:
- Promote code reusability through inheritance.
- Improve code organization and readability.
- Enable encapsulation, protecting data from unintended access.
- Support polymorphism, allowing flexible and interchangeable code.
- Make it easier to model real-world entities and relationships.
DRY Principle in OOP
- DRY stands for "Don't Repeat Yourself".
- It is a software development principle aimed at reducing repetition of code.
- In Object-Oriented Programming (OOP), DRY encourages the use of classes, inheritance, and methods to encapsulate behavior and data, so that code is not duplicated.
# Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
class Cat(Animal):
def speak(self):
print("Cat meows")
By using inheritance, we avoid repeating common code and follow the DRY principle.
Table of Contents
Class :
- In Python, a class is a blueprint for creating objects (instances).
- Classes are created using class keyword
- It defines attributes (variables) and methods (functions) that the objects will have.
Attributes can be accessed using dot . operator (e.g., MyClass.my_attribute).
Example: Defining a simple class
# define a class
class Dog:
sound = "bark" # class attribute
Object: An object is a specific instance of a class. It holds its own set of data (instance variables) and can invoke methods defined by its class. Multiple objects can be created from same class, each with its own unique attributes.
class Dog:
sound = "bark"
dog1 = Dog() # Creating object from class
print(dog1.sound) # Accessing the class
The init() Method
- init() is a special method in Python classes. It’s called the constructor and runs automatically when you create a new instance of a class. Its main job is to initialize the object’s attributes.
Example:
class Dog:
def __init__(self, name):
self.name = name
my_dog = Dog("Rex")
print(my_dog.name) # Output: Rex
Self Parameter
The self parameter in Python is used in instance methods of classes. It refers to the object (instance) itself, allowing you to access its attributes and other methods.
Key points:
- self is always the first parameter in instance methods.
- It is not a keyword; you could name it anything, but self is the convention.
- It lets you distinguish between instance variables and local variables.
class Dog:
def __init__(self, name):
self.name = name # 'self.name' is an instance variable
def bark(self):
print(f"{self.name} says woof!")
dog1 = Dog("Buddy")
dog1.bark() # Output: Buddy says woof!
class Person:
def init(self, name):
self._name = name # private attribute
# Getter method
def get_name(self):
return self._name
# Setter method
def set_name(self, name):
self._name = name
Important concepts in classes and objects
Getter and setter methods:
-Getter and Setter methods provide controlled access to an object's attributes. In Python, these methods are used to retrieve(getter) or modify(setter) values of private attributes, allowing for data encapsulation.
-Python doesn't have explicit get and set methods like other languages, but it supports this functionality using property decorators.
Getter: Used to access value of an attribute.
Setter: Used to modify value of an attribute.
Let’s see an example of implementing getter and setter methods using @property decorators:
class Dog:
def __init__(self, name, age):
self._name = name # Conventionally private variable
self._age = age # Conventionally private variable
@property
def name(self):
return self._name # Getter
@name.setter
def name(self, value):
self._name = value # Setter
@property
def age(self):
return self._age # Getter
@age.setter
def age(self, value):
if value < 0:
print("Age cannot be negative!")
else:
self._age = value # Setter
Explanation:
- init: Initializes private attributes _name and _age.
- @property name: Returns _name value.
- @name.setter: Updates _name.
- @property age: Returns _age value.
- @age.setter: Updates _age if it’s not negative.
Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. This allows subclasses to modify or extend behavior of inherited methods.
Let’s look at an example of method overriding, where a subclass changes the behavior of an inherited method:
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self): # Method overriding
print("Woof")
dog = Dog()
dog.sound()
Static Methods and Class Methods
Static methods and class methods are bound to the class, not instances of the class.
Static Method: A method that does not require access to instance or class. It’s defined using @staticmethod decorator.
Class Method: A method that receives the class as its first argument (cls). It’s defined using @classmethod decorator.
Examples how to use @staticmethod and @classmethod in python
class Dog:
@staticmethod
def info():
print("Dogs are loyal animals.")
@classmethod
def count(cls):
print("There are many dogs of class", cls)
Dog.info() # Static method call
Dog.count() # Class method call
output
Dogs are loyal animals.
There are many dogs of class
- @staticmethod info(): No access to instance or class; prints a general message.
- @classmethod count(cls): Receives the class as cls and prints a message including the class.
- Dog.info(): Calls static method.
- Dog.count(): Calls class method.
Abstract Classes and Interfaces
An abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide specific implementations.
- Abstract classes are defined using abc module in Python. Let’s see an example of using an abstract class to define a required method for subclasses:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Woof")
dog = Dog()
dog.sound()
Class Variables vs Instance Variables
- Class Variables are shared by all instances of a class. They are defined inside the class but outside any methods.
- Instance Variables are unique to each instance and are defined in init() method.
class Dog:
species = "Canine" # Class variable
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 2)
print(dog1.species) # Accessing class variable
print(dog2.name) # Accessing instance variable
Explanation:
species = "Canine": Class variable shared by all Dog objects.
self.name, self.age: Instance variables unique to each object.
dog1 = Dog(...) / dog2 = Dog(...): Creates two instances with different names and ages.
dog1.species: Accesses the class variable.
dog2.name: Accesses an instance variable.
Python Inheritance
- Inheritance allows us to define a class that inherits all the methods and properties from another class.
- Parent class is the class being inherited from, also called base class.
- Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
- Any class can be a parent class, so the syntax is the same as creating any other class: Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:
class Student(Person):
pass
- pass keyword when you do not want to add any other properties or methods to the class.
Example: Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
keywords
SNo | Keyword | Descriptions |
---|---|---|
1 | _init_ | _init_ method is called automatically every time the class is being used to create a new object. |
2 | pass | pass keyword when you do not want to add any other properties or methods to the class. |
Conclusion: Discussed about object oriented programming in Python with examples
💬 If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it 😀 and follow me in dev.to , linkedin, github
Top comments (0)