OBJECT-ORIENTED PROGRAMMING
Object-oriented programming:  Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications.  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.  The main concept of object-oriented Programming (OOPs) or oops concepts in Python is to bind the data and the functions that work together as a single unit so that no other part of the code can access this data.
Object-oriented programming: OOPs Concepts in Python: Class in Python Objects in Python Polymorphism in Python Encapsulation in Python Inheritance in Python Data Abstraction in Python
Object-oriented programming: Python Class :  A class is a collection of objects.  A class contains the blueprints or the prototype from which the objects are being created.  It is a logical entity that contains some attributes and methods.  To understand the need for creating a class let’s consider an example, 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.
Object-oriented programming: Some points on 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.: Myclass.Myattribute Class Definition Syntax: class ClassName: # Statement-1 . . . # Statement-N
Object-oriented programming: Python Objects: An object consists of: • State: It is represented by the attributes of an object. It also reflects the properties of an object. • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. • Identity: It gives a unique name to an object and enables one object to interact with other objects.
Object-oriented programming: Python Objects: To understand the state, behavior, and identity let us take the example of the class dog. The identity can be considered as the name of the dog. State or Attributes can be considered as the breed, age, or color of the dog. The behavior can be considered as to whether the dog is eating or sleeping.
class Dog: # class attribute attr1 = "mammal" # Instance attribute def __init__(self, name): self.name = name # Driver code # Object instantiation Rodger = Dog("Rodger") Tommy = Dog("Tommy") # Accessing class attributes print("Rodger is a {}".format(Rodger.__class__.attr1)) print("Tommy is also a {}".format(Tommy.__class__.attr1)) # Accessing instance attributes print("My name is {}".format(Rodger.name)) print("My name is {}".format(Tommy.name)) o/p: Rodger is a mammal Tommy is also a mammal My name is Rodger My name is Tommy
Creating Classes and objects with methods: The Dog class is defined with two attributes:  attr1 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.  The speak method is defined within the Dog class. This method prints a string that includes the name of the dog instance.
Python Inheritance  In Python object oriented Programming, 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. The benefits of inheritance are:  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.
class BaseClass: def method(self): return "Base method" class DerivedClass(BaseClass): def method(self): return "Derived method"
Multiple Inheritance  When a class is derived from more than one base class it is called multiple Inheritance.  The derived class inherits all the features of the base case.  Syntax: Class Base1: Body of the class Class Base2: Body of the class Class Derived(Base1, Base2): Body of the class
class Class1: def m(self): print("In Class1") class Class2: def m(self): print("In Class2") class Class3(Class1, Class2): def m(self): print("In Class3") obj = Class3() obj.m() Class2.m(obj) Class3.m(obj) Class1.m(obj)
Decorators  Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class.  Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. Syntax: @decorator def function(args): statements(s)
File Handling in Python  File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations.  Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.  The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, like other concepts of Python, this concept here is also easy and short.
Advantages of File Handling in Python • Versatility: File handling in Python allows you to perform a wide range of operations, such as creating, reading, writing, appending, renaming, and deleting files. • Flexibility: File handling in Python is highly flexible, as it allows you to work with different file types (e.g. text files, binary files, CSV files, etc.), and to perform different operations on files (e.g. read, write, append, etc.). • User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read, and manipulate files. • Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python • Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.). • Security risks: File handling in Python can also pose security risks, especially if the program accepts user input that can be used to access or modify sensitive files on the system. • Complexity: File handling in Python can be complex, especially when working with more advanced file formats or operations. Careful attention must be paid to the code to ensure that files are handled properly and securely. • Performance: File handling operations in Python can be slower than other programming languages, especially when dealing with large files or performing complex operations.
f = open(filename, mode) Where the following mode is supported: 1.r: open an existing file for a read operation. 2.w: open an existing file for a write operation. If the file already contains some data, then it will be overridden but if the file is not present then it creates the file as well. 3.a: open an existing file for append operation. It won’t override existing data.
4.r+: To read and write data into the file. This mode does not override the existing data, but you can modify the data starting from the beginning of the file. 5.w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file to zero length or create a file if it does not exist. 6.a+: To append and read data from the file. It won’t override existing data.
Command Line Arguments in Python  The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments.  Python provides various ways of dealing with these types of arguments. The three most common are:  Using sys.argv  Using getopt module  Using argparse module
Using sys.argv  The sys module provides functions and variables used to manipulate different parts of the Python runtime environment.  This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.  One such variable is sys.argv which is a simple list structure. It’s main purpose are:  It is a list of command line arguments.  len(sys.argv) provides the number of command line arguments.  sys.argv[0] is the name of the current Python script.
Structured text files  Handling structured text files in Python involves reading, parsing, and possibly manipulating data that is formatted in a specific way.  Common types of structured text files include  CSV, JSON,  XML.
CSV Files  CSV (Comma-Separated Values) files are commonly used for tabular data.  Python’s built-in csv module can be used to read and write CSV files.  Reading a CSV File: import csv with open('data.csv', mode='r') as file: reader = csv.reader(file) for row in reader: print(row)
CSV Files  Writing to a CSV File: import csv data = [ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'] ] with open('data.csv', mode='w', newline='') as file: writer = csv.writer(file) writer.writerows(data)
JSON Files  JSON (JavaScript Object Notation) is a popular format for data interchange.  Python’s json module can be used to handle JSON files.  Reading a JSON File: import json with open('data.json', 'r') as file: data = json.load(file) print(data)
Writing to a JSON File: import json data = { 'name': 'Alice', 'age': 30, 'city': 'New York' } with open('data.json', 'w') as file: json.dump(data, file, indent=4)
XML Files  XML (eXtensible Markup Language) is used for a variety of data storage and interchange tasks.  The xml.etree.ElementTree module can be used to parse XML files.  Reading an XML File: import xml.etree.ElementTree as ET tree = ET.parse('data.xml') root = tree.getroot() for child in root: print(child.tag, child.attrib)
Writing to an XML File: import xml.etree.ElementTree as ET data = ET.Element('root') child = ET.SubElement(data, 'child') child.text = 'Some text' tree = ET.ElementTree(data) tree.write('data.xml')
Debugging and testing in python  Debugging and testing are crucial steps in the development process to ensure that your code is functioning as expected. Print Statements:  Simple but effective. Use print() to output variable values and track program flow. x = 10 print(f"The value of x is: {x}")
Debugging and testing in python Logging:  More flexible than print statements.  You can set different logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) and write logs to a file. import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug message")
Debugging and testing in python PDB (Python Debugger):  A built-in interactive debugger. import pdb x = 10 pdb.set_trace() # Execution will pause here print(x)
Debugging and testing in python IDE Debuggers:  Most IDEs (like PyCharm, VS Code) have built-in debuggers that allow you to set breakpoints, step through code, and inspect variables.
Python Testing  Python testing is a fundamental aspect of software development that plays a crucial role in ensuring the reliability, correctness, and maintainability of your code. Why is Python Testing Important?  While writing code, everyone make mistakes and hence, Python testing is very important.  Testing also facilitates easier maintenance and updates by providing a safety net against unintended changes.  Rather then this Python testing also important for Quality Assurance, Reliability, and Cost Effectiveness.
Python Testing Strategies • Unit Testing: Explain the concept of unit testing and its focus on testing individual components or units of code in isolation. • Integration Testing: Discuss integration testing and its role in testing interactions between different components or modules within an application. • Functional Testing: Explore functional testing and its emphasis on testing the functionality and behavior of an application from an end-user perspective. • Acceptance Testing: Introduce acceptance testing and its focus on verifying that the application meets the specified requirements and user expectations. • Exploratory Testing: Touch on exploratory testing as an ad-hoc and unscripted approach to testing that emphasizes human intuition and creativity.

PYTHON OBJECT-ORIENTED PROGRAMMING.pptx

  • 1.
  • 2.
    Object-oriented programming:  ObjectOriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications.  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.  The main concept of object-oriented Programming (OOPs) or oops concepts in Python is to bind the data and the functions that work together as a single unit so that no other part of the code can access this data.
  • 3.
    Object-oriented programming: OOPs Conceptsin Python: Class in Python Objects in Python Polymorphism in Python Encapsulation in Python Inheritance in Python Data Abstraction in Python
  • 4.
    Object-oriented programming: Python Class:  A class is a collection of objects.  A class contains the blueprints or the prototype from which the objects are being created.  It is a logical entity that contains some attributes and methods.  To understand the need for creating a class let’s consider an example, 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.
  • 5.
    Object-oriented programming: Some pointson 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.: Myclass.Myattribute Class Definition Syntax: class ClassName: # Statement-1 . . . # Statement-N
  • 6.
    Object-oriented programming: Python Objects: Anobject consists of: • State: It is represented by the attributes of an object. It also reflects the properties of an object. • Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. • Identity: It gives a unique name to an object and enables one object to interact with other objects.
  • 7.
    Object-oriented programming: Python Objects: Tounderstand the state, behavior, and identity let us take the example of the class dog. The identity can be considered as the name of the dog. State or Attributes can be considered as the breed, age, or color of the dog. The behavior can be considered as to whether the dog is eating or sleeping.
  • 8.
    class Dog: # classattribute attr1 = "mammal" # Instance attribute def __init__(self, name): self.name = name # Driver code # Object instantiation Rodger = Dog("Rodger") Tommy = Dog("Tommy") # Accessing class attributes print("Rodger is a {}".format(Rodger.__class__.attr1)) print("Tommy is also a {}".format(Tommy.__class__.attr1)) # Accessing instance attributes print("My name is {}".format(Rodger.name)) print("My name is {}".format(Tommy.name)) o/p: Rodger is a mammal Tommy is also a mammal My name is Rodger My name is Tommy
  • 9.
    Creating Classes andobjects with methods: The Dog class is defined with two attributes:  attr1 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.  The speak method is defined within the Dog class. This method prints a string that includes the name of the dog instance.
  • 10.
    Python Inheritance  InPython object oriented Programming, 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. The benefits of inheritance are:  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.
  • 11.
    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.
  • 12.
    class BaseClass: def method(self): return"Base method" class DerivedClass(BaseClass): def method(self): return "Derived method"
  • 13.
    Multiple Inheritance  Whena class is derived from more than one base class it is called multiple Inheritance.  The derived class inherits all the features of the base case.  Syntax: Class Base1: Body of the class Class Base2: Body of the class Class Derived(Base1, Base2): Body of the class
  • 14.
    class Class1: def m(self): print("InClass1") class Class2: def m(self): print("In Class2") class Class3(Class1, Class2): def m(self): print("In Class3") obj = Class3() obj.m() Class2.m(obj) Class3.m(obj) Class1.m(obj)
  • 15.
    Decorators  Decorators arevery powerful and useful tool in Python since it allows programmers to modify the behavior of function or class.  Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. Syntax: @decorator def function(args): statements(s)
  • 16.
    File Handling inPython  File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations.  Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.  The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, like other concepts of Python, this concept here is also easy and short.
  • 17.
    Advantages of FileHandling in Python • Versatility: File handling in Python allows you to perform a wide range of operations, such as creating, reading, writing, appending, renaming, and deleting files. • Flexibility: File handling in Python is highly flexible, as it allows you to work with different file types (e.g. text files, binary files, CSV files, etc.), and to perform different operations on files (e.g. read, write, append, etc.). • User–friendly: Python provides a user-friendly interface for file handling, making it easy to create, read, and manipulate files. • Cross-platform: Python file-handling functions work across different platforms (e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.
  • 18.
    Disadvantages of FileHandling in Python • Error-prone: File handling operations in Python can be prone to errors, especially if the code is not carefully written or if there are issues with the file system (e.g. file permissions, file locks, etc.). • Security risks: File handling in Python can also pose security risks, especially if the program accepts user input that can be used to access or modify sensitive files on the system. • Complexity: File handling in Python can be complex, especially when working with more advanced file formats or operations. Careful attention must be paid to the code to ensure that files are handled properly and securely. • Performance: File handling operations in Python can be slower than other programming languages, especially when dealing with large files or performing complex operations.
  • 19.
    f = open(filename,mode) Where the following mode is supported: 1.r: open an existing file for a read operation. 2.w: open an existing file for a write operation. If the file already contains some data, then it will be overridden but if the file is not present then it creates the file as well. 3.a: open an existing file for append operation. It won’t override existing data.
  • 20.
    4.r+: To readand write data into the file. This mode does not override the existing data, but you can modify the data starting from the beginning of the file. 5.w+: To write and read data. It overwrites the previous file if one exists, it will truncate the file to zero length or create a file if it does not exist. 6.a+: To append and read data from the file. It won’t override existing data.
  • 21.
    Command Line Argumentsin Python  The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments.  Python provides various ways of dealing with these types of arguments. The three most common are:  Using sys.argv  Using getopt module  Using argparse module
  • 22.
    Using sys.argv  Thesys module provides functions and variables used to manipulate different parts of the Python runtime environment.  This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.  One such variable is sys.argv which is a simple list structure. It’s main purpose are:  It is a list of command line arguments.  len(sys.argv) provides the number of command line arguments.  sys.argv[0] is the name of the current Python script.
  • 23.
    Structured text files Handling structured text files in Python involves reading, parsing, and possibly manipulating data that is formatted in a specific way.  Common types of structured text files include  CSV, JSON,  XML.
  • 24.
    CSV Files  CSV(Comma-Separated Values) files are commonly used for tabular data.  Python’s built-in csv module can be used to read and write CSV files.  Reading a CSV File: import csv with open('data.csv', mode='r') as file: reader = csv.reader(file) for row in reader: print(row)
  • 25.
    CSV Files  Writingto a CSV File: import csv data = [ ['Name', 'Age', 'City'], ['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles'] ] with open('data.csv', mode='w', newline='') as file: writer = csv.writer(file) writer.writerows(data)
  • 26.
    JSON Files  JSON(JavaScript Object Notation) is a popular format for data interchange.  Python’s json module can be used to handle JSON files.  Reading a JSON File: import json with open('data.json', 'r') as file: data = json.load(file) print(data)
  • 27.
    Writing to aJSON File: import json data = { 'name': 'Alice', 'age': 30, 'city': 'New York' } with open('data.json', 'w') as file: json.dump(data, file, indent=4)
  • 28.
    XML Files  XML(eXtensible Markup Language) is used for a variety of data storage and interchange tasks.  The xml.etree.ElementTree module can be used to parse XML files.  Reading an XML File: import xml.etree.ElementTree as ET tree = ET.parse('data.xml') root = tree.getroot() for child in root: print(child.tag, child.attrib)
  • 29.
    Writing to anXML File: import xml.etree.ElementTree as ET data = ET.Element('root') child = ET.SubElement(data, 'child') child.text = 'Some text' tree = ET.ElementTree(data) tree.write('data.xml')
  • 30.
    Debugging and testingin python  Debugging and testing are crucial steps in the development process to ensure that your code is functioning as expected. Print Statements:  Simple but effective. Use print() to output variable values and track program flow. x = 10 print(f"The value of x is: {x}")
  • 31.
    Debugging and testingin python Logging:  More flexible than print statements.  You can set different logging levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) and write logs to a file. import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug message")
  • 32.
    Debugging and testingin python PDB (Python Debugger):  A built-in interactive debugger. import pdb x = 10 pdb.set_trace() # Execution will pause here print(x)
  • 33.
    Debugging and testingin python IDE Debuggers:  Most IDEs (like PyCharm, VS Code) have built-in debuggers that allow you to set breakpoints, step through code, and inspect variables.
  • 34.
    Python Testing  Pythontesting is a fundamental aspect of software development that plays a crucial role in ensuring the reliability, correctness, and maintainability of your code. Why is Python Testing Important?  While writing code, everyone make mistakes and hence, Python testing is very important.  Testing also facilitates easier maintenance and updates by providing a safety net against unintended changes.  Rather then this Python testing also important for Quality Assurance, Reliability, and Cost Effectiveness.
  • 35.
    Python Testing Strategies •Unit Testing: Explain the concept of unit testing and its focus on testing individual components or units of code in isolation. • Integration Testing: Discuss integration testing and its role in testing interactions between different components or modules within an application. • Functional Testing: Explore functional testing and its emphasis on testing the functionality and behavior of an application from an end-user perspective. • Acceptance Testing: Introduce acceptance testing and its focus on verifying that the application meets the specified requirements and user expectations. • Exploratory Testing: Touch on exploratory testing as an ad-hoc and unscripted approach to testing that emphasizes human intuition and creativity.