In Python, classes and objects are fundamental concepts used for object-oriented programming (OOP). Here's an explanation with examples:
1. Creating a Class:
```python
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Creating an object (instance) of the class
my_dog = Dog(name="Buddy", age=3)
# Accessing attributes and calling methods
print(f"{my_dog.name} is {my_dog.age} years old.")
my_dog.bark()
```
In this example, a `Dog` class is created with an `__init__` method (constructor) to initialize attributes. The class also has a `bark` method.
2. Class Inheritance:
```python
class GoldenRetriever(Dog):
def fetch(self):
print("Fetching the ball!")
# Creating an object of the subclass
my_golden = GoldenRetriever(name="Max", age=2)
# Accessing attributes and methods from the base class and the subclass
print(f"{my_golden.name} is a Golden Retriever.")
my_golden.bark()
my_golden.fetch()
```
Inheritance allows a class to inherit attributes and methods from another class. Here, `GoldenRetriever` is a subclass of `Dog`.
3. Encapsulation:
```python
class Circle:
def __init__(self, radius):
self.__radius = radius
def get_radius(self):
return self.__radius
def set_radius(self, new_radius):
if new_radius > 0:
self.__radius = new_radius
# Creating an object with encapsulated attributes
my_circle = Circle(radius=5)
# Accessing and modifying attributes using getter and setter methods
print(f"Radius: {my_circle.get_radius()}")
my_circle.set_radius(7)
print(f"New Radius: {my_circle.get_radius()}")
```
Encapsulation involves restricting access to certain attributes or methods. Here, the radius attribute is encapsulated with getter and setter methods.
4. Polymorphism:
```python
class Cat:
def make_sound(self):
print("Meow!")
# Polymorphic function
def animal_sound(animal):
animal.make_sound()
# Creating objects of different classes
my_cat = Cat()
my_dog = Dog(name="Rex", age=4)
# Calling the same function with different objects
animal_sound(my_cat)
animal_sound(my_dog)
```
Polymorphism allows objects of different classes to be treated as objects of a common base class. Here, both `Dog` and `Cat` have a `make_sound` method, and the `animal_sound` function can work with objects of different classes.
Classes and objects in Python facilitate code organization, reusability, and the implementation of OOP principles.
0 Comments