- Attributes: Variables associated with the object that hold data. For example, a
Carobject might have attributes likecolor,model, andyear. - Methods: Functions associated with the object that define its behavior. For example, a
Carobject might have methods likestart(),stop(), andaccelerate().
This section covers all the foundational topics related to Object-Oriented Programming (OOP) in Python, including the four pillars, classes, objects, and the key benefits of OOP.
Classes and Objects
| Type | Explanation |
|---|---|
| Class | A blueprint for creating objects. It defines the attributes and behaviours that the created objects will have. |
| Object | An instance of a class. It contains data and methods defined by the class. |
Four Pillars of OOP
Encapsulation
Bundle data (attributes) and methods (behaviours) into a single unit (class). Restricts direct access to some of the object’s components, preventing accidental modification of data. Mainly hiding internal state and implementation details.
Inheritance
A mechanism to create a new class (subclass) that inherits attributes and methods from an existing class (parent class). Allows for code reuse and establishes a relationship between classes.
Polymorphism
The ability to use a single interface to represent different underlying data types. Allows methods to do different things based on the object it is acting upon, via method overriding or method overloading.
Abstraction
Hiding complex internal implementation details and showing only the essential features of the object. Lets developers focus on what to do rather than how to do it.
Benefits of OOP
| Benefit | Explanation |
|---|---|
| Code Reusability | OOP allows for reusing existing code through inheritance, reducing redundancy and improving maintainability. |
| Modularity | Breaks down complex systems into smaller manageable pieces (classes and objects), making code easier to understand, develop, and debug. |
| Flexibility and Scalability | OOP allows for easier modifications and extensions to existing code. New features can be added with minimal changes, making it easier to scale applications. |
| Clear Structure | OOP promotes a clear structure for organizing code, making it easier for teams to collaborate. |