🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

OOP-Deptals-Reviewer-Lessons-1-9.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

CharmingSiren

Uploaded by CharmingSiren

Tags

python programming string manipulation

Full Transcript

CMPE 103 Lesson 1-5 Reviewer by: | 1-6 LESSON 1: String Manipulation STRINGS Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode Programming Example: characters. However, Python does not have...

CMPE 103 Lesson 1-5 Reviewer by: | 1-6 LESSON 1: String Manipulation STRINGS Like many other popular programming languages, strings in Python are arrays of bytes representing Unicode Programming Example: characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Strings are immutable. This means that elements of a string cannot be changed once it has Output: been assigned. We can simply reassign different strings to the same name. >>> my_strin = ‘CPE’ >>> my_strin = 'a' TypeError: 'str' object does not support item assignment. How to access characters in string How to create a string in Python? We can access individual characters using indexing Strings can be created by and a range of characters enclosing characters inside a using slicing. The index single quote or double starts from 0. Trying to access quotes. Even triple quotes can a character out of the index be used in Python but are range will raise an IndexError. generally used to represent The index must be an integer. multiline strings and docstrings. We can't use float or other types, this will result in REPRESENTATION OF STRING: TypeError. >>> s = “Hello Python” This is how Python allows negative Python would index the string: indexing for its sequences. 1 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 The index of -1 refers to the >>>p [4:] ‘ram’ last item, -2 to the second last >>>p = “Program” item, and so on. We can access a range of items in a string by >>>p [3:6] ‘gra’ using the slicing operator (colon). String- Index Error Example: Code: More Functionality Of String Finding Length of string >>> len(“Computer Engineering”) String Concatenation Output: >>>print(“CMPE” + “103”) String Repeat >>>print(“A” * 4 ) AAAA Substring Tests >>>”A” in “Computer” True >>>”pr” in “computer” False >>>”pr” not in “computer” True For example: >>> name1="computer" >>>“Program”[3:5] will result in: ‘gr ’ >>> name2=name1[3:5] >>>“Program”[3:6] will yield: ‘gra’ >>>name2 ‘pu’ >>>p = “Program” >>>p [:4] ‘Prog’ String Method >>>p = “Program” String Methods In Python, a method is a function that is 2 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 defined with respect to a 4. Strip() Method particular object. strip() method is used to remove left Syntax: object.method(arguments) and right padded spaces in a given string. For Example: >>>name1=“ a “ >>>name=“Classic” >>>name1.strip() >>>name.find(“s”) = 3 ‘a‘ Removing left and right spaces for a given string The name is the string object.find is the string method “S” is the method argument 3 is where the “s” first 5. Lower() Method position appears lower() method is used to convert a given string into lower case. More String Methods: >>>name1=“ COMPUTER“ >>>name1.lower() 1. Capitalize() Method computer Capitalizes the first letter of the string. 6. Upper() Method >>>name=“computer” upper() method is used to convert a >>>name.capitalize() given string into upper case. ‘Computer’ >>>name1=“ computer“ >>>name1.upper() 2. Lstrip() COMPUTER lstrip() method is used to remove left padded spaces in a given string 7. Title() Method >>>name1=“ a “ title() method is used to convert a >>>name1.lstrip() given string into a title case. Every first ‘a ‘ character or word of a given string is converted to a title case. >>>name1=“ 3. Rstrip() Methods cpe python syllabus“ >>>name1.title() rstrip() method is used to remove the Cpe Python Syllabus right padded spaces in a given string. >>>name1.rstrip() 8. Swapcase() Method ‘ a’ swapcase() method is toggle the Removing left spaces case. Meaning upper to lower and Removing right spaces lower to upper case. >>>name1=“ Computer “ >>>name1.swapcase() cOMPUTER 3 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Every character case is changed aaaaaaaaaaaaaaaAnandaaaaaa aaaaaaaaaa >>>name.center(20,”*”) 9. Ljust() Method *******Anand******** ljust() method is used to add spaces to the left side of the given string >>>name1=“anand “ 12. Zfill() Method >>>name1.ljust(15) zfill() method is used to fill the zero to a given string ‘anand ’ >>>name1=‘ 123’ Left side padded with spaces >>>name1.zfill(15) Note: string length is 5 and 10 spaces added to the left side of ’00000000000 123’ string Filling Zeros 10. Rjust() Method 13. Find() Method rjust() method is used to add spaces find() method is used to find a to the left side of the given string. particular character or string in a given >>>name1=“anand “ string. >>>name1.rjust(15) >>> name1=“Internet" ‘ anand’ >>> name1.find("e") Left side padded with spaces “3” Note: string length is 5 and 10 e is present at 3rd spaces added to the left side of location (first appearance) in a string given string 11. Center(width, fillchar) Method 14. Count() Method The method center() returns centered count() method is used to determine in a string of length width. Padding is the number of times character or string done using the specified fillchar. appears in a given string. Default filler is a space. Centered >>>name1=“Internet “ string >>>name1.count(“n”) >>>name=“Anand” “2” 2 times n appears in a given >>>name.center(36,”a”) string 4 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 15. Startswith() Method startswith() method is used check Boolean value true or false. string start with particular string or not >>>name2=“123” >>>name1=“Delhi“ >>>name2.isnumeric() >>>name1.startswith(“a”) True False >>name1=“123keyboard“ >>name1.isnumeric() Given string not starting with “a” False Given string not number so false 16. Endswith() Method endswith() method is used check string ends with particular string or not 19. Isdecimal() Method >>>name1=“Dairy“ isnumeric(),isdigit() and isdecimal() methods are used to check if a string >>>name1.endswith(“ry”) is digit (number) or not and returns True Boolean value true or false. Given string ends with “en” >>>name2=“123” >>>name2.decimal() 17. Isdigit() Method True isdigit() method is used to check >>name1=“123keyboard“ string is digit (number) or not and >>name1.isnumeric() returns Boolean value true or false. >>>name2=“123” False >>>name2.isdigit() Given string not number so false True >>name1=“123keyboard“ 20. Isalpha() Method >>name1.isdigit() isalpha() method is used to check if a string is digit or not and returns False Boolean value true or false. Given string not number so false >>>name2=“123” 18. Isnumeric() Method >>>name2.isalpha() isnumeric() is similar to isdigit() False (Given string does not method and is used to check if a string contain string ) is digit (number) or not and returns >>name1=“123computer“ 5 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 >>name1.isalpha() True (Given string is lowercase string ) False (Given string is not a string it contains digits) >>>name3=“Keyboard” 23. Isupper() Method >>>Name3.isalpha() isupper() method is used to check the True (It’s a string ) string that contains all letters in upper case or not, it returns true or false result. 21. Isalnum() Method >>>name2=“Anand” isalnum() method is used to check if >>>name2.isupper() a string is an alphanumeric string or not. False (Given string is not upper case string) >>>name2=“123” >>>name1=“ANAND” >>>name2.isalnum() >>>name1.isupper() True (True Given string is alphanumeric) True (Given string is upper case string ) >>>name1=“123computer“ >>>name1.isalnum() True (True Given string is 24. Isspace() Method alphanumeric ) isspace() method is used to check if a >>>name3=“Praveen” string contains space only or not. >>>name3.isalnum() >>>name2=“ ” True (Given string is >>>name2.isspace() alphanumeric ) True (Given string contains space only ) 22. Islower() Method >>>name1=“Anandalaya Anand “ islower() method is used to check if a >>>name1.isspace() string contains all lower case letters or not, it returns true or false result. False (Given string not containing space only) >>>name2=“Anand” >>>name2.islower() 25. Str() Method False (Given string is not lower case string) str() method is used to convert non >>>name1=“anand“ string data into string type. >>>name1.islower() >>>str(576) 6 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 ‘576’ (576 is number split() method is used to split a string converted to string) according to delimiter. >>>name=“Anandalaya NDDB Campus Anand” 26. Len() Method >>>name.split(“Ca”) len() method is used to get a length of string. [“Anandalaya NDDB”,“ mpus Anand”] >>>len(“Naveen”) Split into several words or substrings 6 ( Gives the string length) according to the delimiter. 27. Max() Method 30. Index() Method Same as find(), but raises an max() method is used to get a max exception if str not found. alphabet of string. >>> name="Sainik“ >>> name.index("a",3,5) >>>max(“Praveen”) ValueError: substring not found v ( Gives max character ) >>> name.index("a",1,5) 1 (Character found, returning 28. Min() Method the position ) min() method is used to get a max alphabet of string. >>>min(“Anand”) 31. Ord() Method A ( Gives min character A because it has ASCII Value 65 ) ord() method is used to get a ASCII value for a character. 29. Split() Method >>ord(“a”) split() method is used to split a string. 97 >>>name=“Anandalaya NDDB (97 is the ASCII value for Campus Anand” character ‘a’ ) >>>name.split() 32. Chr() Method [“Anandalaya”,“NDDB”,“ Campus”,“Anand”] chr() method is used to get a character for an ASCII value. Split into several words or substrings >>chr(97) 7 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 ‘a’ - can be used to store text, images, audio and ( ‘a’ ASCII value is 97) video. - image files are generally available in.jpg,.gif or 33. Replace() Method.png formats. replace(old,new) We cannot use text files to store images as the images do not contain >>> name="Sainik” characters. >>> name.replace(“i",”e”) output: “Saenek” What is File Handling? Computer programs can import data from and export data to LESSON 2: File Handling files outside the code. Your Code → External File What is File? - Read : Get data from a file into - Named location on disk to store your program related information - Write/Append : send data from - Used to permanently store data your program into a file in a non-volatile memory(e..g. Hard disk) File Permissions -The use of files is crucial as RAM is Read (r) - File can be ‘looked at’ by volatile and loses data when the the program but not changed. Error if computer is turned off. the file doesn’t already exist. Append (a) - File can be added to. File In Python, a file operation takes place is created if it doesn’t already exist. in the following order. Write (w) - Overwrites existing data, 1. Open a file starting from the beginning of the file. 2. Read or write (perform operation) File is created if it doesn’t already 3. Close the file exist. File Types: Read From a File : The Algorithm 1. Connect to and open the file - Text Files - used to store a. Give the file name and path characters or strings b. Set the permissions for - Binary Files - store entire data opening in the form of bytes( i.e., a group 2. Read the contents into a variable of 8 bits each ) 3. Output the variable 8 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 4. Close the file. print (f.read()) # Reads the entire file f.close() Read All From A file - How to Code f = open(“text.txt”) print(f.read(5)) # Reads the first 5 characters of the file f.close() readline() – Read and return one line from the file. Reads in at most n bytes if specified. For example: f = open(“text.txt) print(f.readline()) #Reads the first line of the file f.close() readlines() – Read and return a list of lines from the file. Reads in at most n bytes/characters if specified. For example: f = open(“text.txt”) data = f.readlines() for line in data: print(line) Write and Append to a File Read Functions: read(n) – Read at most n characters from the file. Reads till end of file if it is negative or None. For example: f = open(“text.txt”) 9 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Type of Exceptions: Checked (Compile-time) Checked exceptions are checked at compile-time. Exceptions are “checked” because they are subject to the “catch” or “specify requirement” otherwise, the program code will not compile. Examples: Invalid Syntax, Incorrect statements LESSON 3: Exception Handling Unchecked (Runtime) Exception Unchecked exceptions are not checked at compile time. An exception is an error that happens during execution of a Errors are not subject to the program. When that error “catch” or “specify occurs, Python generates an requirement”. exception that can be handled, which avoids your program to It occurs during Runtime crash. Examples: invalid input, invalid Examples: arithmetic operations, number divided by zero IOError - If the file cannot be opened. Handling Unchecked Exception: ImportError - If python cannot find the module try - used to test a block of code for errors ValueError - Raised when a function receives an argument that has the right except - used to handle errors type but an inappropriate value finally - used to execute blocks of code regardless of the result of try and except blocks. 10 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Structure: (input) (output) *** ‘try’ and ‘except’ blocks are always together *** ‘else’ Block: - used to define a block of code to be executed if no errors were raised ‘try’ Block: ‘finally’ Block: - lets you test a block of code for - contains code that will run no errors. Code that might raise an matter what, whether an exception is placed inside it. exception occurs or not. - when the code executes, if an - useful for cleaning up resources, error occurs, the rest of the such as closing files or code inside the try block is releasing locks, which must be skipped, and the interpreter done regardless of whether an moves to the except block. error occurred. ‘except’ Block: - lets you handle the error and Examples: specify the type of exception you want to catch. - if an exception occurs inside the try block that matches the type specified in the except block, the code inside the except block is executed. Without ‘try’ and ‘except’ Blocks: 11 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Top-Down Approach ○ A Single module will be split into several smaller modules ○ General to Specific Bottom-Up approach ○ Lot of small modules will be grouped to form a single large module LESSON 4: INTRODUCTION TO ○ Specific to General OBJECT ORIENTED If the requirements are clear PROGRAMMING at the first instance, we can go for Top-Down approach In circumstances where the Programming Paradigm: requirements may keep on - a fundamental style of computer adding, we go for Bottom-up programming. A way of building the approach structure and elements of computer programs. Limitations of Structured - An approach to solve problems by Programming: using programming languages. a. Structured Programming is hard and takes a long time to master Two widely known: b. It concentrates on doing things. Structured Programming Paradigm: (E.g. Algorithms) based on operations. c. Large programs are divided into Object-Oriented Programming smaller programs called Paradigm: based on data. Functions d. Most of the Functions share global data Structured Paradigm e. Data is accessible from one Dividing a problem into smaller function to another sub-problems. f. Top-down Approach Each sub-problem is then analyzed and a solution for the Illustration: subproblem is obtained. The solutions to all the sub-problems are then combined to solve the overall problem. This process of implementing a structured design is called structured programming. Using function 12 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Function & program is divided Comprises several programs into modules that can be used in other Every module has its own data software. and function which can be called by other modules. It splits the tasks into modular forms which makes the program Each object or module has the simpler and easier to read with data and the instruction of what less lines and codes to do with the data in it. Each program accomplishes certain tasks for a specific reason 4 Pillars of OOP ○ Abstraction (Hides Complexity) Object Oriented Programming ○ Encapsulation (Data Paradigm Security) ○ Inheritance (Code A programming style that is Reusability) focused on objects. ○ Polymorphism (Code ○ Objects have both data Reusability) and methods. ○ Objects of the same class have the same A class and object in python data elements and ➔ Class methods. - The class is a user-defined data ○ Objects send and structure that binds the data members receive messages to and methods into a single unit. invoke action. -Class is a blueprint or code Illustration: template for the object creation. Follows object oriented design; Uses sections in a program to perform certain tasks. Using a class, you can create as many OOP splits the program into objects you want. objects that can be reused into other programs. 13 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 ➔ Object an Object is an instance of a Attributes and Operations class. It is a collection of attributes (variables) and ➔ Attribute - An Attribute is a named methods. We use the object of a property of a class. It has a type. class to perform actions. It describes the range of values that that property may hold. Every Object the following property - Identity: Every object must be uniquely identified - State: An Object has an attribute that represents a state of an object, and it also reflects the property of an object. - Behavior: An object has methods that represent its behavior. ➔ Operation (Function) Python is an Object-Oriented - An Operation is a service that Programming language, so can be requested from any everything in python is treated object of the Class to affect as an object. An Object is a behavior. An Operation can real-life entity. It is the either be a command or a collection of various data and question. A question should functions that operate on those never change the state of the data. object only a command can. The outcome of the Operation ➔ Difference of Class and Object in Illustrations: - depends on the current state of the object. 14 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Create Object of a Class An object is essential to work with the class attributes. The object is created with the class name. When we create an object of the class, it is called instantiation. The object is also called the instance of the class. A constructor is a special method used to create and initialize an object of the class. This method is defined in the class. In python, Object creation is divided into two parts in Object Creation and Object initialization. Class Attributes - Internally, __new__ the In Class, attributes can be is the method that defined into two parts: creates an object - And, using the __init__ Attribute Description Characteristics method we can Type implement a constructor The instance - Bound to Object to initialize the object. variables are attributes attached - Declared inside the Instance to an instance of a __init__ method Variables class. We define instance variables - Not shared by objects in the constructor (each object has its own (the __init__() copy) method of a class) A class variable is a - Bound to the Class variable that is Class declared inside of - Declared inside the Variables class, but outside of class, but outside of any any instance method method or __init__() method. - Shared by all objects of a class 15 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Additional Information Class Methods Every object has its own copy of In Class, we can define the the instance attribute and is following three types of unique to each object. methods. All instances of a class share the class variables. The value of Attribute Description Characteristics a class variable is not varied Type from object to object. Only one copy of the static - Used to access - Bound to Object or modify the variable will be created and object state. - It can modify a shared between all objects of Object state the class. - If we use Instance instance - Can Access and Methods variables inside Modify both class and Accessing Properties and Assigning a method, such instance variables Values methods are called instance methods. An instance attribute can be accessed or modified using the - Used to access - Bound to the Class dot notation: or modify the instance_name.attribute_name. class state. - It can modify a class A class variable is accessed or state - In the method modified using the class name. Class implementation, - Can Access only Methods if we use only Class Variable class variables, then such types - Used to create of methods factory methods should be declared as a class method. - It is a general - Bound to the Class utility method It can’t modify a class that performs a or object state task in isolation. Inside these - Can’t Access or Static methods, we modify the Class and Methods don’t use Instance Variables instance or class variables because this static method doesn’t have access to the class attributes. 16 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Eg. Constructors are primarily used to declare and initialize data members (instance variables) of a class. They are called the moment the object is created to initialize the attributes of an object. Constructors can be methods that initialize attributes or methods that perform a task. Constructors A Constructor is a special __init__() method used to create and initialize an object of a class. It - Is a Special/Reserved Method. is defined within the class and - Gets called as soon as an object is automatically called when a of a class is new object of the class is instantiated/created. instantiated. - Has an argument ‘self’, which refers to the current object. - __new__ : creates a new - Succeeding parameters are object of the class. optional. It can have any number of arguments as - __init__: initializes the defined. object along with its attributes 17 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Eg. Non-Parameterized Constructor Constructor without any arguments or no argument at TYPES OF CONSTRUCTORS all. Used to initialize each object - Default Constructors with default values - Non-Parameterized Doesn’t accept any Constructors arguments/parameters when the - Parameterized Constructors object is created Has a default parameter ‘self’ Default Constructors which refers to the object itself Ensures consistent initialization Automatically provided by across all objects of a class Python when no constructor is without needing to specify defined. values explicitly during object Its only purpose is initializing creation. the object. It only initializes the object without setting any attributes. Eg. Parameterized Constructors Since the attribute “self.num” is not defined, Python used the value of Takes parameters/arguments to “num” as a default value serve as values for the object's attributes. 18 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 The first parameter is ‘self’, This allows us to use the which refers to the object itself. constructor without passing any arguments. Can have any number of Parameters without default additional arguments. values still need an argument when the object is created. Eg. When creating an object, all required parameters must be provided for the code to execute correctly. Note: The ‘self’ keyword in Python is used as the first argument for If the constructor has no constructors and refers to the arguments when the object is current object. created, it will use the default It references the current object values for the attributes. to set attributes for the created It enhances readability and object. clearly defines the default It is not mandatory to be named behaviors and initial states of ‘self’; this is a naming objects within the class convention. definition. Though commonly named self, it can be named anything. Constructors with Default Parameters Python allows us to define constructors with default values. A constructor can either have no parameters or have parameters with default values. 19 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 LESSON 5: Inheritance Inheritance - The process of inheriting the properties of the parent class into a child class is called inheritance. - The existing class is called a base class or parent class and the new class is called a subclass or child class or derived class. - The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class instead of creating it from scratch. - In inheritance, the child class acquires all the data members, properties, and functions from the parent class. - Also, a child class can also Types of Inheritance provide its specific implementation to the Single Inheritance methods of the parent class - In single inheritance, a child class inherits from a How to implement inheritance in single-parent class. Here is Python one child class and one parent class. 20 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Multilevel Inheritance: - In multilevel inheritance, a class inherits from a child class or derived class. Multiple Inheritance Suppose three classes A, B, C. A - In multiple inheritance, one is the superclass, B is the child child class can inherit from class of A, C is the child class of multiple parent classes. Here B. In other words, we can say a is one child class and multiple chain of classes is called parent classes. multilevel inheritance. 21 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Hierarchical Inheritance Hybrid Inheritance - more than one child class is - When inheritance consists of derived from a single parent multiple types or a class. combination of different - one parent class and multiple inheritance is called hybrid child classes. inheritance Python super() function - When a class inherits all properties and behavior from the parent class is called inheritance. In such a case, the inherited class is a sub class and the latter class is the parent class. In child class, we can refer to parent class by using the super() function. Benefits of using the super() function: ▪ We are not required to remember or specify the parent class name to access its methods. ▪ We can use the super() function in both single and multiple inheritances. 22 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 The super() function support code reusability as there is no need to write the entire function In the above example, we create two Method Overriding classes named Vehicle (Parent Class) and Car (Child Class) The class Car In inheritance, all members available extends from the class Vehicle so, all in the parent class are by default properties of the parent class are available in the child class. If the child available in the child class. In addition class does not satisfy the parent class to that, the child class redefined the implementation, then the child class is method max_speed(). allowed to redefine that method by extending additional functions in the Method Overriding child class. This concept is called method overriding. When a child class - In inheritance, all members available method has the same name, same in the parent class are available by parameters, and same return type as a default in the child class. method in its superclass, then the method in the child class is said to - If the child class does not satisfy the override the method in the parent parent class implementation, then the class. child class is allowed to redefine that method by extending additional functions in the child class called method overriding. 23 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Inheritance: Does not require - When a child class method has the inheritance. Usually within the same same name, same parameters, and class. same return type as a method in its superclass, then the method in the Summary: Allows you to create child class is said to override the multiple methods with the same name method in the parent class. but different parameters. (Not directly supported in Python). 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). 24 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 Mock Quiz on Lesson 4 in B) The variable num is not Object-Oriented Programming defined within the __init__ method 1.) What is the primary purpose of a constructor in a class? C) The __init__ method cannot have a self parameter A) To define the methods of a class D) The class Example should B) To declare and initialize data inherit from another class members of a class C) To delete objects of a class 4.) It is a fundamental style of D) To create functions outside computer programming. A way the class of building the structure and elements of computer programs. 2.) Which of the following statements about the __init__ A) Programming Paradigm method is true? B) Structured Paradigm A) It is called when an object is deleted C) Object Oriented B) It is called as soon as an Programming Paradigm object of a class is instantiated D) None of the above C) It can only have one argument D) It is used to perform cleanup activities 5.) A programming style that is focused on objects. A) Programming Paradigm 3.) Identify the issue in the following code snippet: B) Structured Paradigm C) Object Oriented Programming Paradigm D) None of the above 6.) Which of the following is false? A) Object is an instance of a class. A) The __init__ method should B) Class is a blueprint or code not be defined inside the class template for the object creation. 25 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 C) An Attribute is a named 9.) Which of the following is true property of an object. about constructors with default parameters? D) An Operation is a service that can be requested from any A) They cannot have the self object of the Class to affect parameter behavior. B) They allow the constructor to be used without passing any arguments C) They must always have 7.) Which of the following best exactly two parameters describes a default constructor? D) They are used to delete attributes of an object A) A constructor that initializes the object with provided arguments B) A constructor that is 10.) Which of the following is automatically provided by true? Python when no constructor is defined A) An object is essential to work C) A constructor that is used to with the class attributes. delete an object D) A constructor that can B) The constructor is also called perform tasks other than the instance of the class. initializing attributes C) Class methods can access 8.) Which of the following and modify both class and limitations of structured instance variables. programming is false? D) None of the above A) Structured Programming is hard and takes a long time to master 11.) This type of attribute in class is B) Large programs are divided used to access or modify the into smaller programs called object state. Functions A) Instance Methods C) Most of the Functions share B) Class Methods global data C) Static Methods D) Data is not accessible from one function to another D) None of the above 12.) Which of the following is false? 26 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 A) Objects have both data and A) Every object has its own copy methods. of the instance attribute and is unique to each object. B) Objects of the same class have the same data elements B) All instances of a class share and methods. the class variables. The value of a class variable is not varied C) Objects send and receive from object to object. messages to invoke action. C) Only one copy of the static D) None of the above variable will be created and shared between all objects of the class. 13.) Which of the following is a D) None of the above property of an object? A) Every object must be uniquely identified B) An object has an attribute that represents a state of an object, and it also reflects the property of an object. C) An object has methods that represent its behavior. D) All of the above 14.) It is a user-defined data structure that binds the data members and methods into a single unit. A) Object B) Class C) Operation D) Attribute 15.) Which of the following is false? 27 CMPE 103 Lesson 1-5 Reviewer by: | 1-6 ANSWER KEY: 1. B - To declare and initialize data members of a class 2. B - It is called as soon as an object of a class is instantiated 3. B - The variable num is not defined within the __init__ method 4. A - Programming Paradigm 5. C - Object Oriented Programming Paradigm 6. C - An Attribute is a named property of an object. 7. B - A constructor that is automatically provided by Python when no constructor is defined 8. D - Data is not accessible from one function to another 9. B - They allow the constructor to be used without passing any arguments 10. A - An object is essential to work with the class attributes. 11. A - Instance Methods 12. D - None of the above 13. D - All of the above 14. B - Class 15. D - None of the above 28 CMPE 103 Lesson 6-7 Reviewer by: | 1-4 ○ If somebody in your campus tells you to fill an application form, you will fill LESSON 6: ABSTRACTION AND in your details like name, address, ENCAPSULATION which semester,percentage you have got, etc. Recall: ○ If some doctor gives you an Four Main OOP Principles (Pillars of OOP) application to fill the details, you will fill the details like name, address, Encapsulation: Ability or technique of date of birth, blood making the fields in a class private and ○ See in the above example what is the providing access to the fields via common thing? Age, name, address public methods. so you can create the class which Inheritance: Process where one consists of a common thing that is object acquires the properties of called abstract class. That class is not another. Information is made complete and it can be inherited by manageable in a hierarchical order. another class. Data Abstraction: Ability to make a class abstract, one that cannot be instantiated. ENCAPSULATION Polymorphism: Ability of an object to take on many forms. The wrapping up of data and functions into a single unit is known as encapsulation. ABSTRACTION The insulation of the data from direct access by the program is called data Abstractions refers to the act of hiding or information hiding. representing essential features It is the process of enclosing one or without including the background more details from the outside world details or explanations. through access rights. Abstractions provide you a Encapsulation allows us to restrict generalized view of your classes accessing variables and methods or objects by providing relevant directly and prevent accidental data information. modification by creating private data Abstraction is the process of hiding members and methods within a class the working style of an object, and Encapsulation is a way that can restrict showing the information of an access to methods and variables from object in an understandable manner. outside of class. Whenever we are working with the class Examples: and dealing with sensitive data, providing access to all variables used within the class is not a good choice. CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 class Employee: # constructor PUBLIC MEMBER def __init__(self, name, salary, project): # data members Public data members are accessible self.name = name within and outside of a class. All self.salary = salary self.project = project member variables of the class are by default public. Example: # method # to display employee's details class Employee: def show(self): def __init__(self, name, salary, project): # accessing public data member # Public Members print("Name: ", self.name, ", Salary: ", self.salary, self.name = name ", Project: ", self.project self.project = project ) self.salary = salary # method def work(self): emp = Employee("John", 10000, "Python") print(self.name, 'is working on', self.project) # All Public Members are accessible # creating object of a class # from outside the class emp1 = Employee('Jessa', 8000, 'NLP') print(emp.name) print(epm.salary) # calling public method of the class emp1.show() emp1.work() PRIVATE MEMBER ACCESS MODIFIERS We can protect variables in the class - limit access to the variables and by marking them private. To define a methods of a class. private variable, add two underscores 1. Public Member - Accessible anywhere as a prefix at the start of a variable from outside the class name. Private members are accessible 2. Private Member - Accessible within only within the class, and we can’t the class access them directly from the class 3. Protected Member - Accessible within the class and its sub-classes objects. Example: class Employee: Example: def __init__(self, name, salary): self.name = name # Public Member class Employee: self.__salary = salary # Private Member def __init__(self, name, salary, project): self.name = name # Public Member emp = Employee("Jessa", 10000) self._project = project # Protected Member # Accessing private members outside self.__salary = salary # Private Member # Results in an error print('Salary: ', emp.__salary) # -> AttributeError: 'Employee' object has no attribute '__salary' We can access private members from outside of a class using the following two approaches: 2 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 Create public method to access emp = Employee("John", 1000) private members # Access to private member using Name Use name mangling Mangling print(emp._Employee__salary) Public method to access private # Outputs members; access Private members # >>1000 outside of a class using an instance method. Example: class Employee: PROTECTED MEMBER def __init__(self, name, salary): self.name = name # public self.__salary = salary # private Protected members are accessible within the class and also available to its def show(self): sub-classes. To define a protected print(f'Name: {self.name}’, member, prefix the member’s name with a f‘ Salary: {self.__salary}') single underscore _. Protected data # private members are accessible members are used when you implement # from within the class the inheritance and want to allow data members access to only child classes. emp = Employee('John', 50000) # Base Class emp.show() class Company: # Outputs def __init__(self): # >> Name: John, Salary: 50000 self._project = "NLP" # protected member Name Mangling to Access private # Child Class members class Employee(Company): We can directly access private and def __init__(self, name): protected variables from outside of a self.name = name class through name mangling. The super().__init__() # Inheritance name mangling is created on an def show(self): identifier by adding two leading print(f"Name: {self.name}") underscores and one trailing print(f"Project: {self._project}") underscores, like this # Accessing protected member _classname__dataMember, where classname is the current c = Employee("John") class, and data member is the c.show() private variable name. # Outputs: Name: John, Project: NLP Example: # direct access to protected member class Employee: print(c._project) def __init__(self, name, salary): self.name = name # public self.__salary = salary # private 3 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 Information hiding and conditional logic for setting an object attributes class GETTERS AND SETTERS IN PYTHON Student: To implement proper encapsulation in class Student: def __init__ (self, name, stud_no, age): Python, we need to use setters and getters. self.name = name The primary purpose of using getters and self.__stud_no = stud_no setters in object-oriented programs is self.__age = age to ensure data encapsulation. Use the # avoids direct modification getter method to access data members def show(self): and the setter methods to modify the data print(Student Details {self.name, members. In Python, private variables are self.__stud_no}') not hidden fields like in other # getter methods programming languages. The getters and def get_stud_no(self): setters methods are often used when: return self.__stud_no When we want to avoid direct access to private variables # setter methods def set_stud_no(self, number): To add validation logic for setting a value if number > 50: class Student: print('Invalid Student Number. Please set correct student number.') def __init__(self, name, age): else: self.name = name self.__stud_no = number self.__age = age jessa = Student('Jessa', 10, 15) # getter method def get_age(self): jessa.show() return self.__age #>>Student Details ('Jessa', 10) # setter method jessa.set_stud_no(60) def set_age(self, age): #>>Invalid Student Number. Please set the correct self.__age = age student number. stud = Student('John', 21) jessa.set_stud_no(20) jessa.show() # retrieving using getter method #>>Student Details ('Jessa', 20) print(stud.get_age()) # setting using setter method stud.set_age(22) ADVANTAGES OF ENCAPSULATION # retrieving using getter method Security: The main advantage of using print(stud.get_age()) encapsulation is the security of the data. Encapsulation protects an object from unauthorized access. It allows private and 4 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 protected access levels to prevent ADVANTAGES OF POLYMORPHISM accidental data modification. Data Hiding: The user would not be 1. Allows objects of different classes to knowing what is going on behind the be treated as objects of a common scene. They would only be knowing that to superclass during runtime. modify a data member, call the setter 2. It enables flexibility and extensibility in method. To read a data member, call the software design by providing a way to getter method. What these setter and write code that can work with objects getter methods are doing is hidden from of various types without needing to them. know their specific implementations. 3. Simplicity: It simplifies the maintenance of the application by keeping classes separated and preventing them from tightly coupling with each other. POLYMORPHISM USE CASE AND BENEFITS Aesthetics: Bundling data and methods within a class makes code more readable and maintainable. Use Cases 1. Collections: Polymorphism is widely used in Python collections, LESSON 7: POLYMORPHISM such as list or dict. You can store Is the ability of an object to take many various types of objects in the forms. same collection, treating them as In simple words, it allows us to instances of their common perform same action in many different superclass or interface. ways. Example: 2. Method Parameter Flexibility: Jessa acts as an employee when Polymorphism allows methods to she is at the office, acts as a wife accept arguments of different at home, and represents herself types, enabling more generic and differently in different places. reusable code. Therefore she takes different forms as the same person as per the 3. Frameworks and APIs: Many situation. frameworks and libraries utilize polymorphism to allow developers to extend and customize their functionality by implementing specific interfaces or extending base classes. Benefits 1. Flexibility and Extensibility: Polymorphism promotes code flexibility, making it easier to add new features or modify existing ones without altering the existing codebase. 5 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 POLYMORPHISM WITH 2. Code Reusability: By using a INHERITANCE common superclass or interface, you can reuse code across Mainly used with inheritance. In different classes, reducing inheritance a child class inherits the redundancy and improving attributes and methods of a parent maintainability. class. The existing class is called a base class or parent class, and the new 3. Ease of Maintenance: Polymorphic code is often more class is called subclass or child class organized and easier to maintain or derived class. since it follows a more modular and hierarchical structure. POLYMORPHISM IN BUILT-IN FUNCTION len() The built-in function len() calculates the length of an object depending upon its type. If an object is a string it class Vehicle: returns the count of characters, if an def __init__(self, name, color, price): self.name = name object is a list, it returns the count of self.color = color items in a list. Behavior example: self.price = price def show(self): print(f"Details: {self.name} {self.color} students = ["Emma", "Jessa", "Kelly"] {self.price}") school = "ABC School" def max_speed(self): print("Vehicle max speed is 150.") # calculate count print(len(students)) # outputs: 3 def change_gear(self): print("Vehicle change 6 gear") print(len(school)) # outputs: 10 class Car(Vehicle): # inherit from Vehicle class def max_speed(self): print("Car max speed is 240") def change_gear(self): print("Car change 7th gear") # Car Object car = Car('Car x1', 'Red', 20000) car.show() # Outputs: Details: Car x1 Red 20000 car.max_speed() # Outputs: Vehicle max speed is 240 car.change_gear() # Outputs: Car change 7th gear 6 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 By leveraging polymorphism, POLYMORPHISM THROUGH INTERFACES AND METHOD developers can write more modular, IMPLEMENTATIONS maintainable, and scalable code.This process of re-implementing the inherited method in the child class Polymorphism through interfaces Using method overriding involves defining a set of method polymorphism allows us to define signatures in an interface (abstract methods in the child class that have base class), and multiple classes can the same name as the methods in the implement these methods according to parent class. their specific behaviors. Objects of these classes can then be treated as ADVANTAGES OF METHOD instances of the interface type, OVERRIDING allowing for flexible usage. from abc import ABC, abstractmethod It is effective when we want to extend the functionality by altering the # Interface inherited method. Or the method from class IShape(ABC): the parent class doesn't fulfill the @abstractmethod needs of a child class, so we need to def draw(self): re-implement the same method in the pass child class in a different way. Method overriding is useful when a # Classes implementing the IShape interface class Circle(IShape): parent class has multiple child classes, def draw(self): and one of those child classes wants to print("Drawing a circle") redefine the method. The other child classes can use the parent class class Square(IShape): method. Due to this, we don't need to def draw(self): modify the class code. print("Drawing a square") In polymorphism, Python's first checks the object's class type and execute the if __name__ == "__main__": appropriate method when we call the circle = Circle() method square = Square() The process of calling the same method with different parameters is circle.draw() square.draw() known as Method Overloading. Python does not support method overloading as it only considers the latest defined POLYMORPHISM THROUGH METHOD method even if you overload the OVERRIDING method. Python will raise a TypeError if In Python, polymorphism is also you overload a method achieved through method overriding and method implementations in def addition(a,b): interfaces (which are represented c = a + b return c using abstract base classes or ABCs). 7 CMPE 103 Lesson 6-7 Reviewer by: | 1-6 and 1-4 def addition(a,b,c): d = a + b + c return d # This line will call the second addition method print(addition(3,7,5)) # 15 class Shape: def area(self, a, b=0): if b > 0: print('Area of rectangle is: ', a*b) else: print('Area of square is: ', a**2) square = Shape() square.area(5) rectangle = Shape() rectangle.area(5, 3) 8 CMPE 103 Lesson 8: Graphical User Interface with Tkinter Reviewer by: | 1-4 4. Call the main event loop so that the actions LESSON 8: GRAPHICAL USER can take place on the user’s computer INTERFACE WITH TKINTER screen. Graphical User Interface – an application that contains widgets (buttons, windows, etc.) that the user can interact with. Example: Web Browser. Top-level Root – window created on top of other window/s. Widgets – objects or components like text labels, buttons, list boxes, etc. that are contained in a window. Sample Output Program: Tkinter (Tea-Kay-inter) – most commonly used GUI method and easiest toolkit to begin with for GUI programming. A standard library for creating desktop-based applications. To create a Tkinter window application: 1. Import the tkinter module. ***TAKE NOTE: Tkinter – Python 2.x; tkinter – Python 3.x 2. Create the main application window. After importing the tkinter module, depending on how you import the library, create the main window (aptly named ‘root’ or ‘root’) by creating a tkinter object that with the tkinter class “Tk()” or tkinter.Tk() After creating the main window, add 3. Add the widgets to the window. components or widgets. After adding widgets, run the application by calling the “mainloop()” method on the main window (Tk) CMPE 103 Lesson 8: Graphical User Interface with Tkinter Reviewer by: | 1-4 “bold”) which sets the font into WINDOW CONFIGURATION Roboto, size 12, and in bold style. width - sets the width in pixels by There are ways to customize your windows but the providing numeric values most common ones are: height - sets the height in pixels by providing numeric values geometry() - determines the size of the state - determines whether a widget window is interactive or disabled. “normal” - minsize() - sets a minimum display size for interactive; “disabled” - the app unresponsive. maxsize() - sets a maximum display size for command - set to the function call the app which is scheduled when the title() - creates the title for the app function is called. iconbitmap() - sets an image file to be the image - enables you to display an app’s icon displayed on the top left once image by providing the path to an opened. image file or by using the Tkinter config(option/s) - used to get some changes PhotoImage object to set the image. done in the window/ widget where it will anchor - determines the positioning be used. For example: by using “n”, “e”, “w”, “s” as the values each representing north, east, west, south, respectively. relief - allows you to set the appearance of a widget’s border. The common relief styles are: - RAISED/”raised” - SUNKEN/ “sunken” - GROOVE/ “groove” - RIDGE/ “ridge” Refer here: parameters for config() Additionally, config() takes options like: GEOMETRY MANAGER METHODS IN TKINTER bg - allows you to set the 1. pack() method - used to organize background color by specifying its components or widgets in the main window color name or the hexadecimal code and determines how much a widget can of a color (e.g. #808080 for gray). occupy a space. fg - allows you to set the foreground color by specifying its color name or Syntax: widgetname.pack(options) the hexadecimal code of a color (e.g. #008000 for green). Options that can be used to manipulate the font - defines the font family, size, placement of the widgets using pack() and style provided in a string or method: tuple. For example, (“Roboto”, 11, CMPE 103 Lesson 8: Graphical User Interface with Tkinter Reviewer by: | 1-4 side - chooses which side of the window the widget will be placed. - LEFT/ “left” - RIGHT/”right” - TOP/”top” (DEFAULT) - BOTTOM/”bottom” - expand - determines the vertical or horizontal space a widget can occupy - True/ TRUE - False/ FALSE fill - sets how much space the widget will occupy - “x” - takes up the whole horizontal space - “y” - takes up the whole vertical space - “both” - takes up both the vertical and horizontal space - None(default) padx - creates space around the horizontal space of the widget pady - creates space around the vertical space of the widget ipadx - expands the horizontal space of the widget ipady - expands the vertical space of the widget ***Note: You can combine different sides but the order of the pack call matters. For detailed explanation and samples: pack()method reference CMPE 103 Lesson 8: Graphical User Interface with Tkinter Reviewer by: | 1-4 2. grid() method - organizes the methods in a northeast, while “news” will make it tabular form by specifying the rows and stick to the center. columns as the options. Syntax: widgetname.grid(options) Options that can be used to utilize the grid() method: column - vertical placement of the widget. By default is 0, which is placed at the leftmost of the window. columnspan - how many column/s the widget occupies (default = 1). row - horizontal placement of the widget. By default is 0, which is placed at the topmost of the window. rowspan - how many row/s the widget occupies(default = 1). padx - number of pixels (in x-axis) to pad the widget outside the widget’s border. pady - number of pixels (in y-axis) to pad the widget outside the widget’s border. ipadx - expands the horizontal space of the widget ipady - expands the vertical space of the widget sticky - determines what side/s will be filled. - “n” - widget will stick at the north side of the window. - “e” - widget will stick at the east side of the window. - “w” - widget will stick at the west side of the window. - “s” - widget will stick at the south side of the window. **You can also combine these directions if you want to have a more precise direction in organizing the widget. Example: “ne” for CMPE 103 Lesson 8: Graphical User Interface with Tkinter Reviewer by: | 1-4 ***Note: Widgets can occupy multiple cells designated position. The values and have padding. range from 0 to 1. - relx - relative x value For detailed explanation and samples: - rely - relative y value grid()method reference - relwidth - relative width value 3. place() method - organizes the widgets to - relheight - relative height the specific x and y coordinates. value Syntax: widgetname.place(x,y) For detailed explanation and samples: x - horizontal offset in pixels place()method reference y - vertical offset in pixels anchor - controls which point the widget is going to be placed ADDITIONAL INFO: COMBINING TKINTER - ?

Use Quizgecko on...
Browser
Browser