Object-Oriented Programming (OOP) is a programming paradigm that allows you to structure your code using objects and classes. Python supports OOP, making it a powerful tool for creating scalable and reusable code. In this tutorial, we’ll introduce you to the basics of OOP in Python.
A class is a blueprint for creating objects. It defines the attributes and methods that the objects created from it will have. Here's how to define a simple class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
An object is an instance of a class. Here's how to create an object from the Person
class:
person1 = Person("Alice", 30)
person1.greet()
Output:
Hello, my name is Alice and I am 30 years old.
Class attributes are shared across all instances, while instance attributes are unique to each instance. Here's an example:
class Circle:
pi = 3.14 # Class attribute
def __init__(self, radius):
self.radius = radius # Instance attribute
def area(self):
return Circle.pi * self.radius ** 2
circle1 = Circle(5)
print(circle1.area())
Output:
78.5
Inheritance allows you to create a class that inherits the attributes and methods of another class:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")
dog = Dog("Buddy")
dog.speak()
Output:
Buddy barks.
Encapsulation involves restricting access to certain attributes and methods using private and protected members:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())
Output:
1500
Polymorphism allows different classes to be treated as instances of the same class through a common interface:
class Cat(Animal):
def speak(self):
print(f"{self.name} meows.")
def animal_sound(animal):
animal.speak()
cat = Cat("Whiskers")
animal_sound(cat)
Output:
Whiskers meows.
Practice creating your own classes and objects. Experiment with inheritance, encapsulation, and polymorphism to better understand OOP principles. Happy coding!