OOP Lesson 1-5.docx
Document Details
Uploaded by CalmFuchsia
Polytechnic University of the Philippines
Tags
Related
- CMPE-103-Module-4-Introduction-to-Object-oriented-Programming.pdf
- CMSC 203 Module 2 - Object-Oriented Programming PDF
- Introduction to Object-Oriented Programming (OOP) PDF
- Introduction to Object-Oriented Programming (OOP) PDF
- Programming in Python for Business Analytics Lecture Notes PDF
- Python Programming Quiz Questions PDF
Full Transcript
LESSON 1: String Manipulation ============================= **STRINGS** - - - - - ***[How to create a string in Python? ]*** - **[REPRESENTATION OF STRING:]** \>\>\> s = "Hello Python" This is how Python would index the string: ![](media/image20.png) **Programming Example:** *...
LESSON 1: String Manipulation ============================= **STRINGS** - - - - - ***[How to create a string in Python? ]*** - **[REPRESENTATION OF STRING:]** \>\>\> s = "Hello Python" This is how Python would index the string: ![](media/image20.png) **Programming Example:** **Output:**![](media/image16.png) **[How to access characters in string]** - - - **Example:** **Code:** ![](media/image44.png) **Output:** **For example:** \>\>\>"Program"\[3:5\] will result in: 'gr ' \>\>\>"Program"\[3:6\] will yield: 'gra' \>\>\>p = "Program" \>\>\>p = "Program" \>\>\>p = "Program" **[String- Index Error]**![](media/image50.png) **[More Functionality Of String]** - \>\>\> len("Computer Engineering") - \>\>\>print("CMPE" + "103") - \>\>\>print("A" \* 4 ) AAAA - \>\>\>"A" in "Computer" True \>\>\>"pr" in "computer" False \>\>\>"pr" not in "computer" True \>\>\> name1=\"computer\" \>\>\> name2=name1\[3:5\] \>\>\>name2 'pu' **[String Method]** - **Syntax**: object.method(arguments) **For Example:** The name is the string object.find is the string method "S" is the method argument 3 is where the "s" first position appears **[More String Methods:]** 1. **Capitalizes** the first letter of the string. 2. **lstrip() metho**d is used to remove left padded spaces in a given string 3. **rstrip() method** is used to remove right padded spaces in a given string. 4. **strip() method** is used to remove left and right padded spaces in a given string. 5. **lower() method** is used to convert a given string into lower case. 6. **upper() method** is used to convert a given string into upper case. 7. **title() method** is used to convert a given string into a title case. Every first character or word of a given string is converted to title case. \>\>\>name1=" cpe python syllabus" \>\>\>name1.title() 8. **swapcase() method** is toggle the case. Meaning upper to lower and lower to upper case. cOMPUTER Every character case is changed 9. **ljust() method** is used to add spaces to the left side of the given string 10. **rjust() method** is used to add spaces to the left side of the given string. \>\>\>name1="anand " 11. **The method center()** returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space. Centered string 12. **zfill() method** is used to fill the zero to a given string 13. **find() method** is used to find a particular character or string in a given string. 14. **count() method** is used to determine the number of times character or string appears in a given string. \>\>\>name1="Internet " 15. **startswith() method** is used check string start with particular string or not Given string not starting with "a" 16. **endswith() method** is used check string ends with particular string or not 17. **isdigit() method** is used to check string is digit (number) or not and returns Boolean value true or false. 18. **isnumeric()** is similar to isdigit() method and is used to check if a string is digit (number) or not and returns Boolean value true or false. \>\>\>name2="123" 19. **isnumeric(),isdigit() and isdecimal() methods** are used to check if a string is digit (number) or not and returns Boolean value true or false. \>\>\>name2="123" 20. **isalpha() method** is used to check if a string is digit or not and returns Boolean value true or false. \>\>\>name2="123" 21. **isalnum() method** is used to check if a string is an alphanumeric string or not. 22. **islower() method** is used to check if a string contains all lower case letters or not, it returns true or false result. 23. **isupper() method** is used to check the string that contains all letters in upper case or not, it returns true or false result. 24. **isspace() method** is used to check if a string contains space only or not. \>\>\>name2=" " True (Given string contains space only ) False (Given string not containing space only) 25. **str() method** is used to convert non string data into string type. \>\>\>str(576) 26. **len() method** is used to get a length of string. 27. **max() method** is used to get a max alphabet of string. 28. **min() method** is used to get a max alphabet of string. 29. **split() method** is used to split a string. split() method is used to split a string according to delimiter. Split into several words or substrings according to the delimiter. 30. Same as **find()**, but raises an exception if str not found. 31. **ord() method** is used to get a ASCII value for a character. 32. **chr() method** is used to get a character for an ASCII value. 33. **replace(old,new)** +-----------------------------------------------------------------------+ | LESSON 2: File Handling | | ======================= | +-----------------------------------------------------------------------+ What is **File**? - - -The use of files is crucial as RAM is volatile and loses data when the computer is turned off. In Python, a file operation takes place in the following order. 1\. **Open** a file 2\. **Read** or write (perform operation) 3\. **Close** the file **File Types:** - - We cannot use text files to store images as the images do not contain characters. What is **File Handling?** - Your Code → External File - - **File Permissions** **Read (r)** - File can be 'looked at' by the program but not changed. Error if the file doesn't already exist. **Append (a)** - File can be added to. File is created if it doesn't already exist. **Write (w)** - Overwrites existing data, starting from the beginning of the file. File is created if it doesn't already exist. **Read From a File : The Algorithm** 1\. **Connect** to and **open the file** a\. **Give the file name** and path b\. **Set the permissions** for opening 2\. **Read the contents** into a variable 3\. **Output** the variable 4\. **Close** the file. **Read All From A file - How to Code** **Read Functions:** **[read(n)]** ***-- Read at most n characters from the file. Reads till end of file if it is negative or None***. **[readline() ]** ***-- Read and return one line from the file. Reads in at most n bytes if specified.*** **[readlines()]** *-- **Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.*** **Write and Append to a File**![](media/image34.png) +-----------------------------------------------------------------------+ | LESSON 3: Exception Handling | | ============================ | +-----------------------------------------------------------------------+ **Exception** - **Examples:** **[IOError]** - If the file cannot be opened. **[ImportError]** - If python cannot find the module **[ValueError]** - Raised when a function receives an argument that has the right type but an inappropriate value **Type of Exceptions:\ \ [Checked (Compile-time)]** - - **Examples:** Invalid Syntax, Incorrect statements **[Unchecked (Runtime)]** - - - **Examples:** invalid input, invalid arithmetic operations, number divided by zero **Handling Unchecked Exception:** - - - **Structure:** ![](media/image7.png) **'try' Block:** - - **'except' Block:** - - Without 'try' and 'except' Blocks: ================================== ![](media/image47.png) \*\*\* **'try' and 'except' blocks are always together \*\*\*** **'else' Block:** - **'finally' Block:** - - Examples: ![](media/image3.png) +-----------------------------------------------------------------------+ | LESSON 4: INTRODUCTION TO OBJECT ORIENTED PROGRAMMING | | ===================================================== | +-----------------------------------------------------------------------+ **Programming Paradigm:** **-** a fundamental style of computer programming. A way of building the structure and elements of computer programs. \- An approach to solve problems by using programming languages**.** **Two widely known:** **[Structured Programming Paradigm:]** based on operations. **[Object-Oriented Programming Paradigm:]** based on data. **Structured Paradigm** - - - - - - - - - - - - **Limitations of Structured Programming:** a. b. c. d. e. f. **Illustration**: - - - - - **Object Oriented Programming Paradigm** - - - - **Illustration:** ![](media/image39.jpg) - - - - - - - - - **A class and object in python** - \- The class is a user-defined data structure that binds the data members and methods into a single unit. -Class is a **blueprint or code template for the object creation.** Using a class, you can create as many objects you want. - Every **Object** the following property - - - - - ![](media/image51.png) **Attributes and Operations** - - - - - **Create Object of a Class** - - - - - **Class Attributes** - +-----------------------+-----------------------+-----------------------+ | **Attribute Type** | **Description** | **Characteristics** | +=======================+=======================+=======================+ | **Instance | The instance | **-** Bound to Object | | Variables** | variables are | | | | attributes attached | **-** Declared inside | | | to an instance of a | the \_\_init\_\_ | | | class. We define | method | | | instance variables in | | | | the constructor (the | **-** Not shared by | | | \_\_init\_\_() method | objects (each object | | | of a class) | has its own copy) | +-----------------------+-----------------------+-----------------------+ | **Class Variables** | A class variable is a | **-** Bound to the | | | variable that is | Class | | | declared inside of | | | | class, but outside of | **-** Declared inside | | | any instance method | the class, but | | | or \_\_init\_\_() | outside of any method | | | method. | | | | | **-** Shared by all | | | | objects of a class | +-----------------------+-----------------------+-----------------------+ **Additional Information** - - - **Accessing Properties and Assigning Values** - - **Class Methods** - +-----------------------+-----------------------+-----------------------+ | **Attribute Type** | **Description** | **Characteristics** | +=======================+=======================+=======================+ | **Instance Methods** | **-** Used to access | **-** Bound to Object | | | or modify the object | | | | state. | \- It can modify a | | | | Object state | | | **-** If we use | | | | instance variables | \- Can Access and | | | inside a method, such | Modify both class and | | | methods are called | instance variables | | | instance methods. | | +-----------------------+-----------------------+-----------------------+ | **Class Methods** | \- Used to access or | \- Bound to the Class | | | modify the class | | | | state. | \- It can modify a | | | | class state | | | \- In the method | | | | implementation, if we | \- Can Access only | | | use only class | Class Variable | | | variables, then such | | | | types of methods | \- Used to create | | | should be declared as | factory methods | | | a class method. | | +-----------------------+-----------------------+-----------------------+ | **Static Methods** | \- It is a general | \- Bound to the Class | | | utility method that | | | | performs a task in | It can't modify a | | | isolation. Inside | class or object state | | | these methods, we | | | | don't use instance or | \- Can't Access or | | | class variables | modify the Class and | | | because this static | Instance Variables | | | method doesn't have | | | | access to the class | | | | attributes. | | +-----------------------+-----------------------+-----------------------+ ![](media/image2.png) **Constructors** - - - Eg. - - - **\_\_init\_\_()** - - - - Eg.![](media/image8.png) **TYPES OF CONSTRUCTORS** - - - **Default Constructors** - - - Eg. Since the attribute "**self.num**" is not defined, Python used the value of "**num**" as a default value **Non-Parameterized Constructor** - - - - - ![](media/image32.png) **Parameterized Constructors** - - - - ![](media/image6.png) **Note:** - - - - **Constructors with Default Parameters** - - - - Eg. - - +-----------------------------------------------------------------------+ | LESSON 5: Inheritance | | ===================== | +-----------------------------------------------------------------------+ **Inheritance** - - - - - **How to implement inheritance in Python**(Kies) ![](media/image1.png) ![](media/image45.png) **Types of Inheritance** **Single Inheritance** - **Multiple Inheritance** - ![](media/image5.png) ![](media/image5.png) **Multilevel Inheritance:** - ![](media/image54.png) ![](media/image26.png) **Hierarchical Inheritance** - - ![](media/image41.png) **Hybrid Inheritance** - ![](media/image52.png) **Python super() function** - **Benefits of using the super() function:** **Method Overriding** In inheritance, all members available in the parent class are by default available in the child class. If the child class does not satisfy the parent class implementation, then the child class is allowed to redefine that method by extending additional functions in the child class. This concept is called method overriding. When a child class method has the same name, same parameters, and same return type as a method in its superclass, then the method in the child class is said to override the method in the parent class. ![](media/image13.png) In the above example, we create two classes named Vehicle (Parent Class) and Car (Child Class) The class Car extends from the class Vehicle so, all properties of the parent class are available in the child class. In addition to that, the child class redefined the method max\_speed().![](media/image24.png) **Method Overriding** \- In inheritance, all members available in the parent class are available by default in the child class. \- If the child class does not satisfy the parent class implementation, then the child class is allowed to redefine that method by extending additional functions in the child class called method overriding. \- When a child class method has the same name, same parameters, and same return type as a method in its superclass, then the method in the child class is said to override the method in the parent class. **Definition**: Subclass provides a specific implementation of a method already defined in its superclass. **Purpose**: To change or extend the behavior of an inherited method. **Method Signature**: Must have the same name and parameters as the method in the superclass. **Inheritance**: Requires a class hierarchy (Inheritance). **Summary**: Used when you need to change the behavior of inherited methods in a subclass. **Method Overloading** **Definition**: Defining multiple methods in the same scope (usually in the same class) with the same name but different signatures (number or type of parameters). **Purpose**: To allow different ways to call a method with different parameters. **Method Signature**: Must have the same method name but different parameters (not directly supported in Python). **Inheritance**: Does not require inheritance. Usually within the same class. **Summary**: Allows you to create multiple methods with the same name but different parameters. (Not directly supported in Python). ### **Mock Quiz on Lesson 4 in Object-Oriented Programming** 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. **ANSWER KEY:** 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.