Python Lecture - 10 Lecture Topics Class and Object Inheritance Polymorphism Iterators Useful Functions (lambda, map, filter)
Python Classes and Objects Class: A blueprint for creating objects (instances) Object: An instance of a class with attributes and methods Example: 01 class Car: color = “black” Audi = Car() print ( Audi.color )
Example: 02 class Student: def __ init __(self, fname , lname , tuition): self.first_name = fname self.last_name = lname self. tuition = tuition def myfunc (self): print ( "Hello my name is " + self.first_name ) student_1= Student( “Jane“ , “Smith” , 20000 ) student_1.myfunc() student_2= Student( “John“ , “ Deo ” , 20000 ) student_2.myfunc() Output: Hello my name is Jane Hello my name is John #The __ init __() Function The __ init __() function in Python initializes object properties and performs necessary setup when an object is created from a class.
The __str__() Function WITHOUT the __str__() function class Person: def __ init __(self, name, age): self.name = name self.age = age p1 = Person( "John" , 36 ) print (p1) Output <__ main__.Person object at 0x15039e602100> WITH the __str__() function class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f "{self.name}({self.age})" p1 = Person( "John" , 36 ) print (p1) Output John(36)
Self parameter The self parameter is a reference to the current instance of the class Used to access variable It does not have to be named self It has to be the first parameter of any function class Person: def __init__(asif, name, age): asif.name = name asif.age = age def myfunc(abc): print ( "Hello my name is " + abc.name) p1 = Person( "John" , 36 ) p1.myfunc()
Modify or Delete Object and using pass p1.age = 40 del p1.age # delete variable del p1 # delete object class Person: pass class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.
Inheritance in Python Allows a class to inherit attributes and methods from another class Supports code reuse and enhances functionality Parent/Base/Super class is the class being inherited from, also called base class Child/Sub class is the class that inherits from another class, also called derived class
Child Class class Student(Person): pass Add the __ init __() function to the Student class: class Student(Person): def __ init __(self, fname , lname ): #add properties etc. The child's __ init __() function overrides the base __ init __ To keep the inheritance of the parent's __ init __() function, add a call to the parent's __ init __() function: class Student(Person): def __ init __(self, fname , lname ): Person.__ init __(self, fname , lname )
Without super() function class Person: def __ init __(self, fname , lname ): self . firstname = fname self . lastname = lname def printname (self): print( self. firstname , self . lastname ) class Student(Person): pass x = Student ("Mike", "Olsen") x. printname () class Person: def __ init __(self, fname , lname ): self. firstname = fname self. lastname = lname def printname (self): print( self. firstname , self. lastname ) class Student(Person): def __ init __(self, fname , lname ): super(). __ init __ ( fname , lname ) x = Student(" Mike ", " Olsen ") x. printname () #Use the super() Function The super() function that will make the child class inherit all the methods and properties from its parent:
Polymorphism in Python • Polymorphism allows functions and objects to act in multiple ways based on the context. • A common example is method overriding.
Polymorphism means "many forms“ Refers to methods/functions/operators with the same name len() function Return the length of string, list, tupple Polymorphism is often used in Class methods Multiple classes with the same method name
Polymorphism: Class class Car: def __init__(self, brand, model): self.brand = brand self.model = model def move(self): print ( "Drive!" ) class Boat: def __init__(self, brand, model): self.brand = brand self.model = model def move(self): print ( "Sail!" ) class Plane: def __init__(self, brand, model): self.brand = brand self.model = model def move(self): print ( "Fly!" ) car1 = Car( "Ford" , "Mustang" ) #Create a Car class boat1 = Boat( "Ibiza" , "Touring 20" ) #Create a Boat class plane1 = Plane( "Boeing" , "747" ) #Create a Plane class for x in (car1, boat1, plane1): x.move()
Polymorphism: Inheritance Class Parent Class: Vehicle, Child Class: Car, Boat, Plane class Vehicle: def __init__(self, brand, model): self.brand = brand self.model = model def move(self): print ( "Move!" ) class Car(Vehicle): pass class Boat(Vehicle): def move(self): print ( "Sail!" ) class Plane(Vehicle): def move(self): print ( "Fly!" ) car1 = Car( "Ford" , "Mustang" ) #Create a Car object boat1 = Boat( "Ibiza" , "Touring 20" ) #Create a Boat object plane1 = Plane( "Boeing" , "747" ) #Create a Plane object for x in (car1, boat1, plane1): print (x.brand) print (x.model) x.move()
Without Polymorphism With Polymorphism
Python Iterators Iterator: An object that can be iterated upon, returning data one element at a time Used in loops, and typically used with functions like __ iter __() and __next__()
Mytuple = (“ I ", “ am ", " coding “, “ and ”, “ learning ”) x = iter ( Mytuple ) print ( next (x)) print ( next (x)) print ( next (x)) print ( next (x)) print ( next (x)) for i in x: # using for print (i)
Iterator Creation class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): x = self.a self.a += 1 return x myclass = MyNumbers() myiter = iter (myclass) print ( next (myiter)) print ( next (myiter)) print ( next (myiter)) print ( next (myiter)) print ( next (myiter)) StopIteration ( after 20 iterations) class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 20 : x = self.a self.a += 1 return x else : raise StopIteration myclass = MyNumbers() myiter = iter (myclass) for x in myiter: print (x)
Useful Functions lambda() Mainly used to create a function without a name Can be used with filter() and map() Only have one expression but may have multiple arguments lambda arguments : expression x = lambda a : a + 10 print (x( 5 )) # 15
map() Function Takes function and a list as input Performs operation on the entire list and return the result in a new list Syntax: map( function , iterables ) Parameter Description function Required. The function to execute for each item iterable Required. A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable .
Map() Function
filter () function Used to create a list of elements for which a function returns “True” Syntax: filter( function , iterable ) Parameter Description function A Function to be run for each item in the iterable iterable The iterable to be filtered
filter () function Example
Exercise Time
Exercise Combine map() and filter() to first filter out all the negative numbers from a list of integers, and then square the remaining numbers. For example, given [-1, 2, -3, 4], the output should be [4, 16]. Write a single line of code that uses filter() to get all the words longer than 4 letters from a list, and map() to convert them to uppercase. Create a list of tuples where each tuple contains a name and an age. Use filter() to get all tuples where the age is greater than 18, then use map() to create a list of names of those individuals.
2. Map Function Exercises: - Problem 4: Given a list of temperatures in Celsius, use map() to convert them to Fahrenheit. The conversion formula is: F = (9/5)*C + 32. - Problem 5: Create a list of strings representing numbers. Use map() to convert these strings into integers. - Problem 6: Use map() to compute the lengths of a list of words. For example, for the list ["apple", "banana", "cherry"], the output should be [5, 6, 6]. 3. Filter Function Exercises: - Problem 7: Given a list of integers, use filter() to extract all the even numbers from the list. - Problem 8: Write a program that takes a list of strings and uses filter() to return only those strings that have more than 5 characters. - Problem 9: Use filter() to remove all negative numbers from a given list of integers.
Exercise: lambda Write a lambda function that takes two numbers and returns their product. Test the function with different pairs of numbers. Create a lambda function that checks if a given string is a palindrome (reads the same forwards and backwards). Use the function to test the strings "radar" and "hello". Write a lambda function that takes a list of integers and returns the maximum value in the list.
Exercise: map and filter Map Given a list of temperatures in Celsius, use map() to convert them to Fahrenheit. The conversion formula is: F = (9/5)*C + 32. Create a list of strings representing numbers. Use map() to convert these strings into integers. Use map() to compute the lengths of a list of words. For example, for the list ["apple", "banana", "cherry"], the output should be [5, 6, 6]. Filter Given a list of integers, use filter() to extract all the even numbers from the list. Write a program that takes a list of strings and uses filter() to return only those strings that have more than 5 characters. Use filter() to remove all negative numbers from a given list of integers.
Reference Foundations of Data Science with Python by John M. Shea Python Data Science Handbook by Jake VanderPlas Python Basics: A Practical Introduction to Python 3 by David Amos Dan, Joanna Jablonski, Fletcher Heisler Internet Resources ( geeksforgeeks , tutorialpoint , w3schools, datacamp ) Online Courses (Udemy, Udacity, Coursera, Harvard eduX )