Introduction to Object-Oriented Programming (OOP) - Programming Concepts

Summary

This document introduces the fundamental concepts of Object-Oriented Programming (OOP). It covers key topics such as classes and objects, encapsulation, inheritance, polymorphism, and abstraction. The material also includes practical examples using Python and practice problems to reinforce the learning experience.

Full Transcript

Introduction to Object-Oriented Programming (OOP) Introduction to Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) is a programming paradigm that structures code by organizing it into "objects," which represent real-world entities or abstract concepts. The...

Introduction to Object-Oriented Programming (OOP) Introduction to Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) is a programming paradigm that structures code by organizing it into "objects," which represent real-world entities or abstract concepts. These objects encapsulate data (attributes) and behavior (methods), enabling developers to create modular, reusable, and maintainable code. Key Concepts of OOP Classes and Objects Encapsulation Inheritance Polymorphism Abstraction Classes and Objects Class: is a blueprint of objects, encapsulating attributes and methods. The class keyword is used to create a class in Python. Syntax: class ClassName: class definitions cannot be empty, but if # class definition you for some reason have a class definition with no content, put in the pass statement class Car: to avoid getting an error Objects: is an instance of a class. Syntax: objectName = ClassName() car1 = Car() Classes and Objects Example # define a class class Car: name = “ ” gear = 4 # create object of class car1 = Car() # Modify the object properties #access attributes and assign new values car1.name = “audi“ car1.name = "Swift" #delete the object properties car1.gear del car1.name #delete the object print(f"Name: {car1.name}, Gears: {car1.gear} ") del car1 Class with Multiple Objects Example: # define a class class Car: name = “” gear = 4 # create multiple objects of class car1 = Car() car2 =Car() #access attributes and assign new values car1.name = "Swift" car1.gear =4 car2.name = "audi" car2.gear =5 print(f"Name: {car1.name}, Gears: {car1.gear} ") print(f"Name: {car2.name}, Gears: {car2.gear} ") Class with Methods # define a class class Car: name = “” quantity = None price = None The self parameter is a def carprice(self): reference to the current instance print(self.quantity * self.price) of the class, and is used to access variables that belong to # create object of class the class. car1 = Car() Class methods must have the #access attributes and assign new values first argument named as self. car1.name = "Swift" Python provides its value car1.quantity =2 automatically. car1.price = 200000 The self argument refers to the car1.carprice() object itself. Practice Problem: 1 Write a Python program to define a class Rectangle with the following features: 1. Attributes: o length (float): The length of the rectangle. o width (float): The width of the rectangle. 2. Methods: o area(): Calculates and returns the area of the rectangle. o perimeter(): Calculates and returns the perimeter of the rectangle. Write a program to: 3. Create an object of the Rectangle class with length=10 and width=5. 4. Calculate and display the area and perimeter of the rectangle. Practice Problem: 1 (Solution) class Rectangle: length ="" width ="" def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) # Create an object of Rectangle rect = Rectangle() rect.length=10 rect.width =5 # Calculate and display area and perimeter print("Area of the rectangle:", rect.area()) print("Perimeter of the rectangle:", rect.perimeter()) Public and Private Data Members Public variables are those variables that are defined in the class and can be accessed from anywhere in the program, of course using the dot operator. Private variables, on the other hand, are those variables that are defined in the class with a double score prefix (__). These variables can be accessed only from within the class and from nowhere outside the class. class ABC(): def __init__(self, var1, var2): self.var1 = var1 self.__var2 = var2 # Private variable def display(self): print("From class method, Var1 =", self.var1) print("From class method, Var2 =", self.__var2) obj = ABC(10, 20) obj.display() print("From main module, Var1 =", obj.var1) # The next line will raise an AttributeError because __var2 is private print("From main module, Var2 =", obj.__var2) Private Methods Like private attributes, you can even have private methods in your class. Usually, we keep those methods as private which have implementation details. So like private attributes, you should also not use private method from anywhere outside the class. However, if it is very necessary to access them from outside the class, then they are accessed with a small difference. A private method can be accessed using the object name as well as the class name from outside the class. The syntax for accessing the private method in such a case would be. objectname._classname__privatemethodname class ABC(): def __init__(self, var): self.__var = var # Private variable def __display(self): # Private method print("From class method, Var =", self.__var) obj = ABC(10) obj._ABC__display() # Accessing the private method using name mangling Calling a Class Method from Another Class Method class ABC(): def __init__(self, var): self.var = var # Private variable def display(self): # Private method print("From class method, Var =", self.var) def add2 (self): self.var +=2 self.display() obj = ABC(10) obj.add2() The __init__() Method (The Class Constructor) The __init__() method has a special significance in Python classes. The __init__() method is automatically executed when an object of a class is created. The method is useful to initialize the variables of the class object. Note the __init__() is prefixed as well as suffixed by double underscores. The __init__() Method (The Class Constructor) class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) # Create an object of Rectangle rect = Rectangle(10, 5) # Calculate and display area and perimeter print("Area of the rectangle:", rect.area()) print("Perimeter of the rectangle:", rect.perimeter()) Other Special Methods __repr__(): __ The __repr__() function is a built-in function with syntax repr(object). It returns a string representation of an object. The function works on any object, not just class instances. __cmp__(): The __cmp__() function is called to compare two class objects. __len__(): The __len__() function is a built-in function that has the syntax, len(object). It returns the length of an object. class ABC(): def __init__(self, name, var): self.name = name self.var = var def __repr__(self): return repr(self.var) def __len__(self): return len(self.name) def __cmp__(self, obj): return self.var - obj.var obj = ABC("abcdef", 10) print("The value stored in object is : ", repr(obj)) print("The length of name stored in object is : ", len(obj)) obj1 = ABC("ghijk1", 1) val = obj.__cmp__(obj1) if val == 0: print("Both values are equal") elif val == -1: print("First value is less than second") else: print("Second value is less than first")

Use Quizgecko on...
Browser
Browser