Let's explain Object-Oriented Programming (OOP) concepts in Python
1. **Classes and Objects** 📦🐕
- **Class**: A blueprint for creating objects.
```
class Dog: # 📦
def __init__(self, name, age):
self.name = name
self.age = age
```
- **Object**: An instance of a class.
```
my_dog = Dog("Buddy", 3) # 🐕
```
2. **Attributes and Methods** 🔧📜
- **Attributes**: Variables that belong to a class or an instance.
```
class Dog:
species = "Canis lupus familiaris" # 🧬 Class attribute
def __init__(self, name, age):
self.name = name # 📛 Instance attribute
self.age = age
```
- **Methods**: Functions defined inside a class.
```
class Dog:
def bark(self): # 🔊 Instance method
print(f"{self.name} says Woof!")
```
3. **Inheritance** 👨👦🐾
Inheritance allows one class to inherit attributes and methods from another class.
```
class Animal: # 👨👦
def __init__(self, species):
self.species = species
class Dog(Animal): # 🐾
def __init__(self, name, age):
super().__init__("Canine")
self.name = name
self.age = age
```
4. **Encapsulation** 🔒📥
Encapsulation is the bundling of data and methods within one unit, restricting direct access to some components.
```
class Dog:
def __init__(self, name, age):
self._name = name # 🔒 Protected attribute
self.__age = age # 🔒 Private attribute
def get_age(self): # 📥
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
```
5. **Polymorphism** 🎭🛠️
Polymorphism allows different classes to be treated as instances of the same class through a common interface.
```
class Animal:
def make_sound(self): # 🎭
pass
class Dog(Animal):
def make_sound(self): # 🐶🔊
print("Woof!")
class Cat(Animal):
def make_sound(self): # 🐱🔊
print("Meow!")
def animal_sound(animal): # 🛠️
animal.make_sound()
```
6. **Abstraction** 🕵️♀️🔍
Abstraction means hiding complex implementation details and showing only the necessary features.
```
from abc import ABC, abstractmethod
class Animal(ABC): # 🕵️♀️
@abstractmethod
def make_sound(self): # 🔍
pass
class Dog(Animal):
def make_sound(self): # 🐶🔊
print("Woof!")
```
Comments