






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
in this lab manual you will get all the codes of the questions and task of the lab manual number 7 of object oriented programming
Typology: Assignments
1 / 12
This page cannot be seen from the preview
Don't miss anything!







1 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented
Lab 05 – Introduction to Inheritance and Multi-Inheritance Objectives:
As we have practiced many times. We can access the attributes inside the parent class or we can change the value of the parameter during the creation of object. Here we have the Revise Exercise to teach how we can change the variable values from age and name. Revise Exercise 1: Write a class of Boy and Girl, each Boy or Girl classes have name, age and gender as parameters. The objects then can change the values inside it. class Boy: name ="" gender ="Male" age = 20 class Girl: name ="" gender ="Female" age = 18 Irtiza = Boy() Ahmed = Boy() Arisha = Girl() Ayesha = Girl() print("My name is : " + "Irtiza") Irtiza.gender print(Irtiza.gender) Irtiza.age = 21 print(Irtiza.age)
2 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented print("My name is : " + "Ahmed") Ahmed.gender print(Ahmed.gender) Ahmed.age = 22 print(Ahmed.age) print("My name is : " + "Arisha") Arisha.gender print(Arisha.gender) Arisha.age = 19 print(Arisha.age) print("My name is : " + "Ayesha") Ayesha.gender print(Ayesha.gender) Ayesha.age =18 print(Ayesha.age) Exercise 2: Write a class for an arbitrary POS, where we can calculate the number of initiations of each object and can also calculate once to object is deleted. class POS: counter = 0 def init (self): type(self).counter += 1 def del (self): type(self).counter -= 1 if name == " main ": x1 = POS() print("Number of instances: : " + str(POS.counter)) x2 = POS() print("Number of instances: : " + str(POS.counter)) x3 = POS() print("Number of instances: : " + str(POS.counter)) del x2 print("Number of instances: : " + str(POS.counter)) del x1 print("Number of instances: : " + str(POS.counter)) Object-oriented programming creates reusable patterns of code to curtail redundancy in development projects. One way that object-oriented programming achieves recyclable code is through inheritance, when one subclass can leverage code from another base class. In this lab will go through some of the major aspects of inheritance in Python, including how parent classes and child classes work, how to override methods and attributes, how to use the super() function, and how to make use of multiple inheritance.
4 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented self.first_name = first_name self.last_name = last_name def swim(self): print("The fish is swimming.") def swim_backwards(self): print("The fish can swim backwards.") We have added the methods swim() and swim_backwards() to the Fish class, so that every subclass will also be able to make use of these methods. Since most of the fish we’ll be creating are considered to be bony fish (as in they have a skeleton made out of bone) rather than cartilaginous fish (as in they have a skeleton made out of cartilage), we can add a few more attributes to the init () method: Exercise 4: Extends the previous fish class with skeleton as bone or cartilage. class Fish: def init (self, first_name, last_name="Fish", skeleton="bone", eyelids=False): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim(self): print("The fish is swimming.") def swim_backwards(self): print("The fish can swim backwards.") Building a parent class follows the same methodology as building any other class, except we are thinking about what methods the child classes will be able to make use of once we create those.
Child or subclasses are classes that will inherit from the parent class. That means that each child class will be able to make use of the methods and variables of the parent class. For example, a Goldfish child class that subclasses the Fish class will be able to make use of the swim() method declared in Fish without needing to declare it. We can think of each child class as being a class of the parent class. That is, if we have a child class called Rhombus and a parent class called Parallelogram, we can say that a Rhombus is a Parallelogram, just as a Goldfish is a Fish. The first line of a child class looks a little different than non-child classes as you must pass the parent class into the child class as a parameter:
5 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented class Trout(Fish): The Trout class is a child of the Fish class. We know this because of the inclusion of the word Fish in parentheses. With child classes, we can choose to add more methods, override existing parent methods, or simply accept the default parent methods with the pass keyword, which we’ll do in this case: class Trout(Fish): pass We can now create a Trout object without having to define any additional methods. Exercise 5: Extending the Fish class create a class of Trout which is child to its parent class (Fish). class Trout(Fish): pass terry = Trout("Terry") print(terry.first_name + " " + terry.last_name) print(terry.skeleton) print(terry.eyelids) terry.swim() terry.swim_backwards() We have created a Trout object terry that makes use of each of the methods of the Fish class even though we did not define those methods in the Trout child class. We only needed to pass the value of "Terry" to the first_name variable because all of the other variables were initialized. Next, let’s create another child class that includes its own method. We’ll call this class Clownfish, and its special method will permit it to live with sea anemone: Exercise 6: Add another class Clownfish inherited from Fish class. class Clownfish(Fish): def live_with_anemone(self): print("The clownfish is coexisting with sea anemone.") The output shows that the Clownfish object casey is able to use the Fish methods init () and swim() as well as its child class method of live_with_anemone(). If we try to use the live_with_anemone() method in a Trout object, we’ll receive an error: Output terry.live_with_anemone() AttributeError: 'Trout' object has no attribute 'live_with_anemone' This is because the method live_with_anemone() belongs only to the Clownfish child class, and not the Fish parent class.
7 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented sammy = Shark("Sammy") print(sammy.first_name + " " + sammy.last_name) sammy.swim() sammy.swim_backwards() print(sammy.eyelids) print(sammy.skeleton) We have overridden the initialized parameters in the init () method, so that the last_name variable is now set equal to the string "Shark", the skeleton variable is now set equal to the string "cartilage", and the eyelids variable is now set to the Boolean value True. Each instance of the class can also override these parameters. The method swim_backwards() now prints a different string than the one in the Fish parent class because sharks are not able to swim backwards in the way that bony fish can. We can now create an instance of the Shark child class, which will still make use of the swim() method of the Fish parent class: The Shark child class successfully overrode the init () and swim_backwards() methods of the Fish parent class, while also inheriting the swim() method of the parent class. When there will be a limited number of child classes that are more unique than others, overriding parent class methods can prove to be useful.
With the super() function, you can gain access to inherited methods that have been overwritten in a class object. When we use the super() function, we are calling a parent method into a child method to make use of it. For example, we may want to override one aspect of the parent method with certain functionality, but then call the rest of the original parent method to finish the method. In a program that grades students, we may want to have a child class for Weighted_grade that inherits from the Grade parent class. In the child class Weighted_grade, we may want to override a calculate_grade() method of the parent class in order to include functionality to calculate a weighted grade, but still keep the rest of the functionality of the original class. By invoking the super() function we would be able to achieve this. The super() function is most commonly used within the init () method because that is where you will most likely need to add some uniqueness to the child class and then complete initialization from the parent.
8 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented To see how this works, let’s modify our Trout child class. Since trout are typically freshwater fish, let’s add a water variable to the init () method and set it equal to the string "freshwater", but then maintain the rest of the parent class’s variables and parameters: Exercise 8: class Trout(Fish): def init (self, water = "freshwater"): self.water = water super(). init (self) We have overridden the init () method in the Trout child class, providing a different implementation of the __init () that is already defined by its parent class Fish. Within the init () method of our Trout class we have explicitly invoked the init () method of the Fishclass. Because we have overridden the method, we no longer need to pass first_name in as a parameter to Trout, and if we did pass in a parameter, we would reset freshwater instead. We will therefore initialize the first_name by calling the variable in our object instance. Now we can invoke the initialized variables of the parent class and also make use of the unique child variable. Let’s use this in an instance of Trout: terry = Trout()
= "Terry"
print(terry.first_name + " " + terry.last_name) print(terry.eyelids)
The output shows that the object terry of the Trout child class is able to make use of both the child- specific init () variable water while also being able to call the Fish parent init () variables of first_name, last_name, and eyelids. The built-in Python function super() allows us to utilize parent class methods even when overriding certain aspects of those methods in our child classes.
10 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented Programming Exercise (Python) Task 1: Discuss in detail what you understand by inheritance, Multi-inheritance, Multilevel inheritance and Super(), for all the exercises and tasks starting from task 2. Task 2 : Create class and sub classes for different types of frequent airline travelers with different connecting flights. Use concept of Multiple inheritance and Super(). CODE: class Passenger_Plane: def init(self,name,flight_num,capacity): self.name=name self.flight_num=flight_num self.capacity=capacity def get_details(self): print(f'Flight Name: {self.name}\nFlight Number: {self.flight_num}\nCapacit y:{self.capacity}') def book_seat(self): self.seat=True class Fighter_Plane: def init(self,name): self.name=name def get_name(self): return self.name def isfighter(self): return True class Plane(Passenger_Plane,Fighter_Plane): def init(self,name,flight_num=None,capacity=None): Passenger_Plane.init(self,name,flight_num,capacity) def get_details(self): super().get_details() emirates=Plane("emirates","ek-224", 450 ) emirates.get_details() fp=Plane("f-16") print(fp.get_name()) print("Is f-16 is the fighter plane:",fp.isfighter())
11 Student Name: Roll No: Section: Prepared By: Syed CS-121 | Object Oriented
class Umbrella: def init(self, size, color): self.size=size self.color=color class categories: def init(self, type, print): self.type=type self.print=print class my_choice(Umbrella, categories): def init(self, size, color, type, print, price): Umbrella.init(self, size, color) categories.init(self, type, print) self.price=price def my_order(self): print("size: {}\ncolor: {}\ntype: {}\nprint: {}\nprice: {}".format(self.siz e, self.color, self.type, self.print, self.price)) obj=my_choice("Large","Black","Parachute","plain", 1000 ) obj.my_order()