Object-Oriented Programming in Python PDF

Summary

The document provides an introduction to object-oriented programming (OOP) using Python. It covers key concepts like classes, objects, inheritance, encapsulation, constructors, and generators, with examples. The content is appropriate for students learning object-oriented programming.

Full Transcript

Unit-3 Part-I Introduction to Object Oriented Programming Contents- Abstraction & Encapsulation: Defining classes, attributes, methods, constructors, destructors, objects, generators Object-oriented programming vs Procedural Programming- Index Object-oriented Programming...

Unit-3 Part-I Introduction to Object Oriented Programming Contents- Abstraction & Encapsulation: Defining classes, attributes, methods, constructors, destructors, objects, generators Object-oriented programming vs Procedural Programming- Index Object-oriented Programming Procedural Programming 1. Object-oriented programming is the Procedural programming uses a list of instructions to do problem-solving approach and used where computation step by step. computation is done by using objects. 2. It makes the development and maintenance In procedural programming, It is not easy to maintain the easier. codes when the project becomes lengthy. 3. It simulates the real world entity. So It doesn't simulate the real world. It works on step by step real-world problems can be easily solved instructions divided into small parts called functions. through oops. 4. It provides data hiding. So it is more secure Procedural language doesn't provide any proper way for than procedural languages. You cannot data binding, so it is less secure. access private data from anywhere. 5. Example of object-oriented programming Example of procedural languages are: C, Fortran, Pascal, languages is C++, Java,.Net, Python, C#, etc. VB etc. OOP in Python- Class The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc. Object The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc. self parameter in python- The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. Example Class and object in Python- Example- Python Constructor- A constructor is a special type of method (function) which is used to initialize the instance members of the class. In C++ or Java, the constructor has the same name as its class, but it treats constructor differently in Python. It is used to create an object. Constructors can be of two types. Parameterized Constructor Non-parameterized Constructor Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task. Creating the constructor in python In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class. We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Example Constructor- Python Parameterized Constructor- The parameterized constructor has multiple parameters along with the self. Python Non-Parameterized Constructor- The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument. Python Default Constructor- When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor. It does not perform any task but initializes the objects. More than One Constructor in Single class- Counting the number of objects of a class- The constructor is called automatically when we create the object of the class. Consider the following example. Python Inheritance- Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class. In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Example Inheritance in Python- Example of method overriding- Super() In Python, super() is a built-in function used to call methods from a parent (or superclass) within a child (or subclass). It helps in code reusability and avoids redundant code when dealing with inheritance. class Vehicle: def __init__(self, brand, speed): self.brand = brand self.speed = speed def show_info(self): print(f"Brand: {self.brand}, Speed: {self.speed} km/h") class Car(Vehicle): def __init__(self, brand, speed, fuel_type): super().__init__(brand, speed) # Call parent constructor self.fuel_type = fuel_type def show_info(self): super().show_info() # Call parent method print(f"Fuel Type: {self.fuel_type}") c = Car("Toyota", 180, "Petrol") c.show_info() Concepts Revise-1. Classes Definition: A class is a blueprint or template for creating objects. Components: Attributes: Variables that store data. Methods: Functions defined within a class that operate on its attributes. Syntax: class ClassName: # Constructor def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2 # Method def display_attributes(self): print(self.attribute1, self.attribute2) Example: class Car: def __init__(self, brand, model, color): self.brand = brand self.model = model self.color = color def description(self): return f"{self.color} {self.brand} {self.model}“ car = Car("Toyota", "Corolla", "Red") print(car.description()) # Output: Red Toyota Corolla 2. Objects Definition: An object is an instance of a class. Example: class Student: def __init__(self, name, age): self.name = name self.age = age student1 = Student("John", 20) # Object creation print(student1.name) # Output: John 3. Attributes Definition: Variables within a class that hold data about the object. Types: Instance Attributes: Specific to an instance of the class. Class Attributes: Shared across all instances of the class. Example: class Circle: pi = 3.14 # Class attribute def __init__(self, radius): self.radius = radius # Instance attribute def area(self): return Circle.pi * (self.radius ** 2) circle = Circle(5) print("Area:", circle.area()) # Output: Area: 78.5 4. Methods Definition: Functions defined within a class that operate on its attributes. Types: Instance Methods: Operate on instance attributes and require self as the first parameter. Class Methods: Operate on class attributes and use the @classmethod decorator. Static Methods: Independent of class or instance attributes; use the @staticmethod decorator. Example: class MathOperations: def add(self, a, b): # Instance method return a + b @classmethod def multiply(cls, a, b): # Class method return a * b @staticmethod def subtract(a, b): # Static method return a - b math = MathOperations() print(math.add(3, 5)) # Output: 8 print(MathOperations.multiply(4, 5)) # Output: 20 print(MathOperations.subtract(10, 7)) # Output: Special Methods: Constructors and Destructors 1. Constructor (__init__) Definition: A special method automatically invoked to initialize attributes of an object. Example: class Person: def __init__(self, name, age): self.name = name self.age = age person = Person("Alice", 25) print(person.name) # Output: Alice Special Methods: Constructors and Destructors 2. Destructor (__del__) Definition: A special method called when an object is destroyed. Example: class Example: def __del__(self): print("Object destroyed") obj = Example() del obj # Output: Object destroyed Encapsulation Definition: Encapsulation is the mechanism of restricting access to certain details of an object and exposing only necessary parts. Key Points: Combines data (attributes) and methods (functions) into a single unit (class). Protects sensitive data through controlled access. Access modifiers in Python: Public: Accessible anywhere. Protected: Accessible within the class and its subclasses (denoted by _). Private: Accessible only within the class (denoted by __). Example- class Employee: def __init__(self, name, salary): self.name = name # Public attribute self._position = "Intern" # Protected attribute self.__salary = salary # Private attribute def get_salary(self): return self.__salary def set_salary(self, salary): if salary > 0: self.__salary = salary emp = Employee("Alice", 30000) print(emp.name) # Output: Alice print(emp.get_salary()) # Output: 30000 emp.set_salary(40000) print(emp.get_salary()) # Output: 40000 Generators in Python- Generators in Python are a special type of iterable that allow you to iterate over values one at a time without storing them all in memory. They are defined using functions and the yield keyword.It is quite simple to create a generator in Python. It is similar to the normal function defined by the def keyword and uses a yield keyword instead of return. Or we can say that if the body of any function contains a yield statement, it automatically becomes a generator function. Why Use Generators? Memory Efficient: Unlike lists, they do not store all values in memory. Lazy Evaluation: Values are generated on the fly, making them useful for large datasets. Improves Performance: Reduces computation time and enhances efficiency. Example-

Use Quizgecko on...
Browser
Browser