0% found this document useful (0 votes)
4 views38 pages

Python (Unit 3)

The document provides an overview of Object-Oriented Programming (OOP) principles, including concepts such as classes, objects, attributes, methods, inheritance, polymorphism, and encapsulation. It explains how these concepts can be applied in Python, detailing the structure and functionality of classes and objects, as well as the importance of data hiding and method overriding. The content is aimed at teaching the fundamentals of OOP to students in a university setting.

Uploaded by

ssathyapriya326
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

Python (Unit 3)

The document provides an overview of Object-Oriented Programming (OOP) principles, including concepts such as classes, objects, attributes, methods, inheritance, polymorphism, and encapsulation. It explains how these concepts can be applied in Python, detailing the structure and functionality of classes and objects, as well as the importance of data hiding and method overriding. The content is aimed at teaching the fundamentals of OOP to students in a university setting.

Uploaded by

ssathyapriya326
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Unit 3 Object Oriented Design PES” 6 Prof. Nitish Rajamane UNIVERSITY Dept. of FOMC nitishrajamane@[Link] Object Oriented Programming Object-Oriented Programming (OOP) is a way of writing computer programs that mimics the way we humans think and interact with the world around us. It's a programming approach that's designed to make software development more Object Oriented Programming Imagine you're building a virtual zoo in a computer program. In traditional programming, you might organize everything using functions and variables. You'd have a function for each animal, like a lion or a tiger, and you'd keep track of their properties (like their name, age, and type) using variables. In Object-Oriented Programming, you'd think of each animal as an "object" and create a blueprint for what an animal should look like. This blueprint includes the animal's characteristics (called "attributes") and the things it can do (called "methods"). So, a lion object would have attributes like its name and age, and methods like "roar" and "eat." Object Oriented Programming * Objects: Think of objects as individual things or entities. In our zoo example, each animal (lion, tiger, etc.) is an object. fa Person i [sie] Name Sex Profession cra] work) study) ‘Blueprint oct objet stud): she ty 5 our week al Be a i Object Oriented Programming * Classes: A class is like a blueprint or template for creating objects. It defines what attributes and methods an object should have. So, you'd have a “Lion" class that defines what a lion should look like. lieeeon ak [= Name Sex Profession work!) study) ep to ene objets | a ae | ste } Se te pes Instance metho. Object Oriented Programming * Attributes: Attributes are a oe the characteristics or ——— Cae , . [am ae: a ws properties of an object. For Pe er Q ———— frstince enables a lion, attributes might @ won svevereiea |) . . as Tagneer AB cy a include its name, age, and ‘iron pa ‘ses |} ae type. ee aD ‘ecm } Foererise Pretest: ctor work() a - Cormac toso fe Object Oriented Programming * Methods: Methods are like the actions or behaviors that an Es object can perform. For a lion, [ce e: ane oe e . methods might include roaring, Person a eee eating, or sleeping. Fa ® eerie ae te 3 PL stay) sh study 10 ne methods Name fevers nese | ---—~ 2 Profession — SS = =a e = suay) GRD Seesricss |] heptane ec De tess 1S Insane methods Object Oriented Programming (cas) (Sates) Name Sex Profession (Ciehaviours) work) study() ‘Slueprnt to create objects GD ne ee p2. ame: tessa ‘Sex Female Profession: Engineer p's instance variables study(): She study 10 hours a week ‘Name: Jon Sex Male Profession: Doctor p's Instance variables work{): He works asa ctor in x12 Hospital study(): she study 15 hours a week Object Oriented Programming = 2 | Person @@&> = Name Sex Profession (Ceehawiours] work() study() ‘lueprint to create objects Se ea — = en sees, @ Instance methods hours @ week } ws Instance variables } ws Object Oriented Programming PES + In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in programming. + It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in the programming. . is to bind the OOP on that pa OOPs Concepts in Python Class Objects Polymorphism Encapsulation Inheritance Data Abstraction OOP Python Class A class is a collection of objects. Aclass contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains some attributes and methods. let's say you wanted to track the number of dogs that may have different attributes like breed, and age. If a list is used, the first element could be the dog’s breed while the second element could represent its age. Let's suppose there are 100 different dogs, then how would you know which element is supposed to be which? What if you wanted to add other properties to these dogs? This lacks organization and it's the exact need for classes. Python Class * Classes are created by keyword class. + Attributes are the variables that belong to a class. + Attributes are always public and can be accessed using the dot (.) operator. Eg.: [Link] Class Definition Syntax: class ClassName # Statement-1 # Statement-N Creating an Empty Class in Python # Python3 program to # demonstrate defining # a class class Dog: pass Class Definition Syntax: class ClassName: # Statement-1 # Statement-N Python Objects PES The object is an entity that has a state and behavior associated with it. It may be any real-world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an object. The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on. You've been using objects all along and may not even realize it. An object consists of PES State: It is represented by the attributes of an object. It also reflects the properties of an object. State or Attributes can be considered as the breed, age, or color of the dog. Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. The behavior can be considered as to whether the dog is eating or sleeping. Identity: It gives a unique name to an object and enables one object to interact with other objects. The identity can be considered as the name of the dog. Creating an Object * This will create an object named obj of the class Dog defined above. Before diving deep into objects and classes let us understand some basic keywords that will we used while working with objects and classes. obj = Dog() Python self 1. Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it 2. If we have a method that takes no arguments, then we still have to have one argument. Python self . Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it 2. If we have a method that takes no arguments, then we still have to have one argument. = [Link] we call a method of this object as [Link](arg1, arg2), this is automatically converted by Python into [Link](myobject, arg1, arg2) - this is all the special self is about. Python__init__Method 1.The__init__ method is run as soon as an object of a class is instantiated. 2. The method is useful to do any initialization you want to do with your object. 3. Now let us define a class and create some objects using the self and _init__method. 4. [Refer Jupyter Notebook] Creating Classes and objects with methods attr is a class attribute set to the value “mammal”. Class attributes are shared by all instances of the class. + __init__is a special method (constructor) that initializes an instance of the Dog class. It takes two parameters: self (referring to the instance being created) and name (representing the name of the dog). The name parameter is used to assign a name attribute to each instance of Dog. Creating Classes and objects with methods The speak method is defined within the Dog class. This method prints a string that includes the name of the dog instance. The driver code starts by creating two instances of the Dog class: Rodger and Tommy. The__init__method is called for each instance to initialize their name attributes with the provided names. The speak method is called in both instances ([Link]() and [Link]()), causing each dog to print a statement with its name. Creating Classes and objects with methods The speak method is defined within the Dog class. This method prints a string that includes the name of the dog instance. The driver code starts by creating two instances of the Dog class: Rodger and Tommy. The__init__method is called for each instance to initialize their name attributes with the provided names. The speak method is called in both instances ([Link]() and [Link]()), causing each dog to print a statement with its name. Python Inheritance * Inheritance is the capability of one class to derive or inherit the properties from another class. + The class that derives properties is called the derived class or child class and the class from which the properties are being derived is called the base class or parent class. Benefits of inheritance + It represents real-world relationships well. * It provides the reusability of a code. We don't have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. + It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. Types of Inheritance Single Inheritance: Single-level inheritance enables a derived class to inherit characteristics from a single-parent class. Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class. Hierarchical Inheritance: Hierarchical-level inheritance enables more than one derived class to inherit properties from a parent class. Multiple Inheritance: Multiple-level inheritance enables one derived class to inherit properties from more than one base class. Types of Inheritance EES We have created two classes i.e. Person (parent class) and Employee (Child Class). The Employee class inherits from the Person class. We can use the methods of the person class through the employee class as seen in the display function in the above code. A child class can also modify the behavior of the parent class as seen through the details() method. PES Python Polymorphism Polymorphism simply means having many forms. For example, we need to determine if the given species of birds fly or not, using polymorphism we can do this using a single function. This code demonstrates the concept of inheritance and method overriding in Python classes. It shows how subclasses can override methods defined in their parent class to provide specific behavior while still inheriting other methods from the parent class. Python Encapsulation or Data Hiding * What is Data Hiding? Data hiding, also known as encapsulation, is a fundamental concept in object-oriented programming (OOP) that allows you to restrict access to certain attributes or methods of a class. It's a way of preventing direct modification of an object's internal data, making it private to the class, and providing controlled access to the outside world. Python Encapsulation or Data Hiding Why Use Data Hiding? Data hiding is crucial for maintaining the integrity and consistency of an object's data. By restricting direct access to attributes, you can prevent unintended modifications and enforce rules and validations. This promotes better code organization, reduces errors, and improves the overall security and maintainability of your code. Python Encapsulation or Data Hiding PES Types of Access Modifiers In Python, data hiding is achieved using access modifiers: Public (default): Attributes and methods are accessible from anywhere, both inside and outside the class. They are not prefixed with an underscore. Protected (_): Attributes and methods are meant to be protected from outside access but can still be accessed if needed. They are prefixed with a single underscore (e.g., variable, method()). Private (__): Attributes and methods are considered private and should not be accessed directly from outside the class. They are prefixed with a double underscore (e.g.,__variable,__method()). Python Encapsulation or Data Hiding Accessing Attributes and Methods Accessing attributes and methods depends on the access modifiers: Public attributes and methods are accessed directly, as shown in the display_marks method. Protected attributes and methods are accessed using the _ prefix, as seen with the _update_rollno method. Private attributes and methods are accessed using the___prefix, as demonstrated with the__add_mark method. Python Encapsulation or Data Hiding PES Benefits of Data Hiding — Enhanced Security: Private attributes and methods are hidden from external access, improving the security of sensitive data. Code Maintenance: Data hiding allows you to make changes to the internal structure of a class without affecting external code that uses the class. : Data hiding promotes the encapsulation of data and methods within a class, reducing code complexity and ensuring a clean interface for external use. Validation and Error Handling: Data hiding enables you to enforce data validation and error handling within the class, ensuring data consistency. Reduced Code Coupling: By exposing only essential attributes and methods, data hiding reduces code coupling, making it easier to maintain and extend your code. What is Method Overriding? * Method overriding is a fundamental concept in object-oriented programming (OOP). * It allows a subclass to provide a specific implementation for a method that is already defined in its parent class. + In other words, a subclass can replace or "override" a method inherited from the parent class to customize its behavior. PES Why Use Method Overriding? + Method overriding is essential for creating specialized versions of methods in a subclass. + Itallows you to adapt and extend the functionality of a parent class without modifying the original class. * This is a crucial feature for building flexible and maintainable code, especially when working with inheritance. How Method Overriding Works + In Python, method overriding is straightforward. + To override a method, you need to define a method in the subclass with the same name and signature as the method you want to override in the parent class. * The overridden method in the subclass will then be called instead of the one in the parent class when the method is invoked on an object of the subclass. Guidelines for Method Overriding The method name and parameters in the subclass must exactly match those in the parent class. The return type of the overriding method can be the same or a subtype of the return type in the parent class. You can use the super() function to call the parent class's method from the overriding method. [Refer Jupyter Notebook] ES) Thank You... Prof. Nitish Rajamane PES Dept. of FOMC untversitty nitishrajamane@[Link] a aa

You might also like