Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. Python supports OOP, making it easier to model real-world scenarios and manage complex systems. This tutorial covers the basics of Python OOP, including classes, objects, methods, and key OOP principles.
Key Concepts in Python OOP
- Class: A blueprint for creating objects.
- Object: An instance of a class.
- Method: A function defined inside a class that operates on objects.
- Attribute: A variable that belongs to an object or class.
1. Creating a Class and an Object
In Python, you can create a class using the class
keyword. An object is created by instantiating the class.
# Defining a class class Person: def __init__(self, name, age): self.name = name # Attribute self.age = age def greet(self): return f"Hello, my name is {self.name} and I am {self.age} years old." # Creating an object person1 = Person("Alice", 30) print(person1.greet()) # Output: Hello, my name is Alice and I am 30 years old.
2. Understanding the __init__()
Method
The __init__()
method is a special method in Python classes. It is called automatically when an object is created and is used to initialize the object’s attributes.
class Car: def __init__(self, brand, model, year): self.brand = brand self.model = model self.year = year def get_description(self): return f"{self.year} {self.brand} {self.model}" car1 = Car("Toyota", "Corolla", 2022) print(car1.get_description()) # Output: 2022 Toyota Corolla
3. OOP Principles in Python
OOP is based on four main principles:
- Encapsulation: Bundling data and methods within a class to protect the data from external modification.
- Inheritance: Creating a new class based on an existing class to reuse code.
- Polymorphism: Defining a common interface for multiple forms (methods or objects).
- Abstraction: Hiding complex implementation details and exposing only the necessary parts.
Example of Inheritance:
# Parent class class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound." # Child class (inherits from Animal) class Dog(Animal): def speak(self): return f"{self.name} barks." dog1 = Dog("Buddy") print(dog1.speak()) # Output: Buddy barks.
Example of Polymorphism:
class Bird: def speak(self): return "Bird chirps." class Cat: def speak(self): return "Cat meows." # Using polymorphism animals = [Bird(), Cat()] for animal in animals: print(animal.speak()) # Output: # Bird chirps. # Cat meows.
4. Access Modifiers (Public, Protected, Private)
Python does not enforce strict access control, but it provides conventions for indicating the intended level of access.
- Public: Accessible from anywhere (default).
- Protected: Prefixed with a single underscore (
_
), indicating that it should not be accessed outside the class or subclass. - Private: Prefixed with a double underscore (
__
), making it harder to access from outside the class.
Example of Access Modifiers:
class BankAccount: def __init__(self, balance): self.balance = balance # Public self._account_number = "123456789" # Protected self.__pin = "1234" # Private def get_balance(self): return self.balance account = BankAccount(1000) print(account.balance) # Output: 1000 print(account._account_number) # Output: 123456789 # print(account.__pin) # Error: 'BankAccount' object has no attribute '__pin'
5. Class vs. Instance Attributes
Instance attributes are specific to an object, while class attributes are shared across all instances of the class.
class Employee: company_name = "TechCorp" # Class attribute def __init__(self, name, salary): self.name = name # Instance attribute self.salary = salary emp1 = Employee("John", 50000) emp2 = Employee("Jane", 60000) print(emp1.company_name) # Output: TechCorp print(emp2.company_name) # Output: TechCorp
Conclusion
Python’s object-oriented programming model provides a robust way to manage and organize code. By understanding classes, objects, and OOP principles, you can write more reusable, maintainable, and scalable Python applications.