Introduction to Python Classes
What are Classes?
A class in Python is a blueprint for creating objects. Objects represent real-world entities or
concepts, with attributes (data) and methods (functions). Using classes helps organize code
in a reusable and modular way.
Defining a Class
To define a class in Python, use the `class` keyword. Here's an example:
class ExampleClass:
def __init__(self, name, age):
self.name = name # Attribute
self.age = age # Attribute
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
Creating Objects
To create an object (or instance) of a class, call the class name as if it were a function:
# Creating an object
person = ExampleClass("Alice", 30)
print(person.greet()) # Output: Hello, my name is Alice and I am 30 years old.
Key Concepts of Classes
1. **Attributes**: Variables that hold data associated with a class or its objects.
2. **Methods**: Functions defined within a class to manipulate its data or perform actions.
3. **The `__init__` Method**: A special method used to initialize objects.
4. **Inheritance**: Mechanism to create a new class based on an existing class.
5. **Encapsulation**: Restricting access to certain details of an object, promoting
modularity.
6. **Polymorphism**: Using a single interface to represent different types.
Inheritance Example
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def speak(self):
return "I make a sound."
class Dog(Animal):
def speak(self):
return "Woof!"
dog = Dog()
print(dog.speak()) # Output: Woof!
Benefits of Using Classes
1. **Modularity**: Classes help in organizing code into reusable modules.
2. **Reusability**: Once a class is written, it can be reused multiple times.
3. **Scalability**: Classes allow for building complex applications by combining simple
objects.
4. **Encapsulation**: Hides implementation details and exposes only necessary features.