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