Classes and Object-Oriented Programming (OOP) in Python Programming language (Part 6/6)
Experience the Beauty of Python: The Easiest Language to Learn and Use
Table of Contents
- Introduction to Object-Oriented Programming
- Classes in Python
- Creating Objects (Instances)
- Class Attributes and Instance Attributes
- Methods in Classes
- Inheritance and Polymorphism
- Encapsulation and Abstraction
- Best Practices for Object-Oriented Programming in Python
- Additional Resources for Learning Python OOP
1. Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that allows us to structure our code using objects, which are instances of classes. This helps us to bind data and methods together.
2. Classes in Python
Class is a template to create objects, objects also called instances of that particular class. It defines the attributes and methods that objects of that class will have.
Let’s take an example to understand it, I am Siddhartha, an instance of Human class. I have properties like my dark black hair and methods like I can code.
3. Creating Objects (Instances)
Syntax: object_name = ClassName()
Example:
class Person:
def __init__(self, name):
self.name = name
person = Person("John") # Creates a Person object with the name "John"
In the example above, the Person class has an __init__ method. This method is automatically called when an object is created from the class. It is also known as the constructor, which means it will help to create an instance of a particular class.
The __init__ method takes in the self parameter, which refers to the instance of the object being created. We can use any other name other than self, using it is just a standard to denote the instance.
Inside the __init__ method, self.name = name assigns the value of the name parameter to the instance attribute self.name.
In the example, person = Person(“John”) creates a Person object with the name “John”.
4. Class Attributes and Instance Attributes
Class attributes are those properties that are shared by all instances(objects) of a class.
Instance attributes are those properties that are shared to each instance individually. they are not shared among other instances.
Example:
class Circle:
pi = 3.14159 # Class attribute: Common value for all circles
def __init__(self, radius):
self.radius = radius # Instance attribute: Specific to each circle
def calculate_area(self):
return self.pi * (self.radius ** 2)
# Creating objects of the Circle class
circle1 = Circle(5) # Creates a circle object with radius 5
circle2 = Circle(10) # Creates a circle object with radius 10
print("Circle 1 - Radius:", circle1.radius) # Output: Circle 1 - Radius: 5
print("Circle 2 - Radius:", circle2.radius) # Output: Circle 2 - Radius: 10
print("Circle 1 - Area:", circle1.calculate_area()) # Output: Circle 1 - Area: 78.53975
print("Circle 2 - Area:", circle2.calculate_area()) # Output: Circle 2 - Area: 314.159
In the example above, Circle class has a class attribute pi. This attribute is shared by all instances of the Circle class.
We then create 2 circle instances called, circle1 and circle2. We can access their attributes using dot notation (circle1.radius, circle2.radius).
We also call the calculate_area method on each circle object to calculate the area of the circles.
5. Methods in Classes
Methods are functions defined inside a class.
Syntax: def method_name(self, parameters):
Example:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
# Creating an object of the Rectangle class
rectangle = Rectangle(5, 10)
# Calling the method to calculate the area
area = rectangle.calculate_area()
# Printing the calculated area
print("Rectangle Area:", area) # Output: Rectangle Area: 50
The calculate_area method is defined inside the class. This method calculates the area of the rectangle.
We can call a method in the same way we access the attribute. For this case, we call the method a rectangle.calculate_area()
These methods can access the instance attributes of the object using the self parameter.
6. Inheritance and Polymorphism
Inheritance allows us to create a new class that has properties and methods from another class, that is already defined. This saves us from defining the same methods again and again for different classes.
Polymorphism enables objects of different classes to be used interchangeably if they have a common interface.
Example:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Creating objects and using polymorphism
dog = Dog()
cat = Cat()
# Calling the speak method on the dog and cat objects
dog_sound = dog.speak()
cat_sound = cat.speak()
# Printing the sounds
print("Dog sound:", dog_sound) # Output: Dog sound: Woof!
print("Cat sound:", cat_sound) # Output: Cat sound: Meow!
In the example above, we have an Animal class that serves as the base or Parent class. It has a speak method defined with a pass statement, indicating that it doesn’t do anything on its own.
The Dog and Cat classes are derived (Child class) from the Animal class. They inherit the speak method from the Animal class and provide their implementation of the speak method. In this way, both classes Dog and Cat have their way of handling speak functionality.
We create objects of the Dog and Cat classes named dog and cat, respectively. We call the speak method on each object and assign the returned value to the variables dog_sound and cat_sound.
The output for dog and cat objects is “Woof!” and “Meow!” respectively.
Through inheritance and polymorphism, objects of different classes (derived from a common base class) can be treated interchangeably when they have a common interface, such as sharing the same method names.
7. Encapsulation and Abstraction
Encapsulation is the practice of binding data and methods to work on those data together.
Abstraction focuses on defining essential features or behaviors while hiding unnecessary implementation details.
Example:
class BankAccount:
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient funds!")
# Using encapsulation and abstraction
account = BankAccount()
# Depositing and withdrawing funds
account.deposit(100) # Deposits 100 to the account
account.withdraw(50) # Withdraws 50 from the account
# Printing the remaining balance
print("Account balance:", account.balance) # Output: Account balance: 50
By using encapsulation, the internal implementation of the BankAccount class and the logic for depositing and withdrawing funds, are hidden from external access. We can interact with the account object through its public methods, the deposit and withdrawal methods.
8. Best Practices for Object-Oriented Programming in Python
- Use short and meaningful class and method names.
- Follow the Single Responsibility Principle, where each class should have a single responsibility and functionality.
- Write unit tests for your classes and methods, we have many libraries in Python for this.
- Ensure proper documentation for your code. Add doc string in class and methods.
9. Additional Resources for Learning Python OOP
- https://docs.python.org/3/tutorial/classes.html
- Udacity — Object-Oriented Programming in Python
- Coursera — Object-Oriented Programming in Python 3
- Real Python — Object-Oriented Programming in Python
Thank You
Thank you for taking the time to read this article on classes and OOP in Python. I hope it provided you with a clear understanding of the concepts and their implementation.
I value your feedback! If you have any comments or questions, please feel free to share them with me on comment or email me directly.
At point to remember is that practice is key to understanding any programming language or concept, so continue practicing Programming in Python. Happy coding!
Link for Part 1: https://medium.com/@siddp6/python-programming-language-part-1-6-8b937f7297bf
Link for Part 2: https://siddp6.medium.com/python-programming-language-part-2-6-403dabaa7c6a
Link for Part 3: https://medium.com/@siddp6/python-programming-language-part-3-6-ab0af8000e27
Link for Part 4: https://medium.com/@siddp6/conditionals-and-loops-python-programming-language-part-4-6-b5b1a8c9521e
Link for Part 5: https://siddp6.medium.com/functions-in-python-programming-language-part-5-6-5c2c5b1df5fe
Link for Part 6: https://siddp6.medium.com/classes-and-object-oriented-programming-oop-in-python-programming-language-part-6-6-4e2fca5e1eb9
Copyright © 2023 Siddhartha Purwar. All rights reserved. Portions of this content were enhanced grammatically and refined with the assistance of ChatGPT, an AI language model by OpenAI.