Lesson 7.3: Attributes and Methods
Introduction:
Attributes and methods are the core components of classes in Python. Attributes store the data associated with an object, while methods define the behavior or actions that objects can perform. Mastering attributes and methods is essential for designing functional OOP programs.
1. Attributes:
-
Attributes represent object properties.
-
Can be instance attributes (specific to an object) or class attributes (shared across all objects).
Example – Instance Attributes:
Example – Class Attributes:
2. Methods:
-
Methods define actions for objects.
-
Instance methods operate on instance attributes.
Example – Instance Methods:
3. Special Methods:
-
Methods with double underscores, e.g.,
__init__,__str__,__len__, are called magic methods. -
They allow customizing object behavior for built-in functions.
Example – __str__ Method:
4. Practical Tips:
-
Use instance attributes for object-specific data
-
Use class attributes for data shared among all objects
-
Keep methods focused on single responsibilities for clarity
Learning Outcome of This Lesson:
-
Understand the difference between instance and class attributes
-
Define and use methods to perform object actions
-
Apply special methods to enhance object behavior
-
Build objects with well-structured data and functionality
