Object-Oriented Programming in Python Notes
Introduction to Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm designed to model real-world scenarios into computer code through the use of objects, which can represent both tangible entities and abstract concepts.
The principles of OOP aim to promote greater efficiency and flexibility in software development by enabling code reuse, enhancing modularity, and facilitating easier maintenance and debugging through encapsulation and abstraction.
Classes and Objects
Class Definition: A class acts as a blueprint or template for creating objects. It defines a set of attributes and methods that the instantiated objects (also known as instances) will possess.
Object (Instance) Definition: An object is an instance created from a class blueprint, inheriting the attributes and behaviors defined by that class. Each instance can maintain its own state and data.
Class Creation and Instantiation: A class is declared using the
classkeyword followed by the class identifier (e.g.,class Student:).To instantiate an object, a call to the class name assigns the new instance to a variable (e.g.,
s1 = Student()). This process allocates memory for the instance, enabling unique attribute values for each object. In the context of object-oriented programming, when you call a function (or the class name in this case) to create an object like `s1 = Student()`, you are essentially invoking the class constructor, which is the `__init__` function. In this process: - The expression `Student()` calls the class `Student`, executing the `__init__()` method if it is defined. - Memory is allocated for a new instance of the `Student` class, and this instance is referred to as `s1`. - Any attributes that are initialized in the `__init__` method are set for this specific instance, allowing `s1` to hold its own unique state/data independent of other instances of the `Student` class. - The variable `s1` now acts as a reference to this new object, allowing you to access its attributes and methods (e.g., `s1.name`, `s1.hello()`). Thus, `s1` serves as a specific representation of the `Student` class, complete with its own set of data as defined by the attributes in the `__init__` constructor.Attributes of an instance can be accessed and modified using dot notation (e.g.,
s1.name).
## Code Example: - Class Definition: python class Student: name = "karan kumar" # Class attribute
- Object Instantiation and Attribute Access:python #Creating object (instance) s1 = Student() print(s1.name) # Outputs: karan kumar
Class and Instance Attributes
Class Attributes: These attributes belong directly to the class itself.
Class attributes are shared across all instances created from the class, meaning any modification will reflect in all instances.
Syntax for access:
Class.attr(e.g.,Student.name).
Instance Attributes:
These attributes belong exclusively to a specific object or instance, which allows each object to maintain distinct values.
Syntax for access:
obj.attr(e.g.,s1.name).
The __init__ Constructor Function and self Parameter
The
__init__()Function: A built-in function present in all Python classes, it serves as a constructor that is automatically executed whenever an object is being initialized or instantiated from a class, allowing the setting of initial values for object attributes.The
selfParameter: This parameter is a reference to the current instance of the class. It is critical as the first parameter in instance methods, enabling access to instance variables or methods unique to the object.
## Code Example:
- Class Creation with __init__ Constructor:python class Student: def __init__(self, fullname): self.name = fullname # Instance attribute
- Object Instantiation Passing Parameters to Constructor:python # Creating object s1 = Student("karan") print(s1.name) # Outputs: karan
Methods in Python Classes
Definition of Methods: Methods are functions that belong to objects and define the behavior of those objects, allowing interaction with their data.
Method Implementation: Methods are defined inside a class using standard function syntax (
def). They requireselfas the first parameter to allow access to the instance data they operate on.Methods can be called using dot notation on an object instance (e.g.,
s1.hello()).
## Code Example: - Defining Constructor and Instance Method:python class Student: def __init__(self, fullname): self.name = fullname def hello(self): print("hello", self.name)
- Instantiation and Method Invocation:python # Creating object s1 = Student("karan") s1.hello() # Outputs: hello karan
Practice Exercise: Student Class and Average Mark Calculation
Task Specification: Create a
Studentclass that takes a student's name and the marks of three subjects as arguments in its constructor (__init__). Include a method within the class to calculate and print the average mark of the three subjects, demonstrating method functionality and object interaction.Mathematical Formula: The average can be calculated using the formula:
Static Methods and Decorators
Static Methods: These methods do not use or require the
selfparameter and operate at the class level rather than at the instance level. Static methods are defined using the@staticmethoddecorator, which indicates that the method does not modify class or instance state.Decorators: Syntax elements that allow for wrapping another function to extend or alter its behavior without modifying the original code permanently. Decorators are versatile and can be used for logging, access control, and more.
## Code Example: - Using @staticmethod Decorator in a Class:python class Student: @staticmethod def college(): print("ABC College")
Core Pillars of OOP: Abstraction and Encapsulation
Abstraction: This practice involves hiding the implementation details of a class while exposing only the essential features and interfaces to the user, simplifying interactions and reducing complexity in usage.
Encapsulation: The practice of wrapping data (attributes) and functions (methods) together into a single unified unit, known as an object, preventing external access to the internal representation and allowing the use of getter and setter methods to control access.
Practice Exercise: Bank Account Management Class
Task Specification: Create an
Accountclass that is initialized with two core attributes:balanceandaccount_no. This class should feature methods to perform the following operations:Debit: Decreases the account balance by a specified amount, ensuring that it does not go below zero.
Credit: Increases the account balance by a specified amount.
Print Balance: Outputs the current account balance in a readable format, utilizing instance methods for user interaction.