Saturday, 8 May 2021

Single Inheritance: Python OOP


What is that we are going to learn?

Have a look at the videos where I learnt from.
Topics that are covered in this Python Video:
0:00 What is Inheritance? 1:44 Implement Inheritance in python 2:33 Derive a class from another class 4:42 Create objects of class 8:24 Benefits of inheritance (code reuse, extensibility, readability )

What is that we are going to learn:

class Vehicle:
    #now lets type in the method. in class, method refers to the functions.
    def general_usage(self):
        print("general use:transportation")
#now I am going to write my subclass and this is called the style of inheritance. In other words, way of inheriting a class into another subclass.
class Car(Vehicle):
    #now i am going to define the constructors or __init__
    def __init__(self):
        print("im car")
        self.wheels = 4
        self.has_roof = True
    def specific_usage(self):
        print("specific use: commute to work, family purpose")
#now lets write our second subclass class, which is again derived from the main class vehicle
class MotorCycle(Vehicle):
    def __init__(self):
        print("im MotorCycle")
        self.wheels = 2
        self.has_roof = False
        
    def specific_usage(self):
        print("specific use: road trip, race")
        

#lets create some objects and see the real benefit of this inheritance.

c = Car()
c.general_usage() #see, i do not have a method inside the sub class Car that says general_usage but I was able to use it because of the inheritance.
c.specific_usage()


m = MotorCycle()
m.general_usage() #see, i do not have a method inside the sub class Car that says general_usage but I was able to use it because of the inheritance.
m.specific_usage()  

 

 

#isinstance method

#Codes: add this following code to the line previous lines of codes.

#isinstance tells you whether can object is an instance of a specific class or not

print(isinstance(c, Car))

#how to know whether a class is a subclass of another class. 

#there is another method called issubclass() for that

print(issubclass(Car, Vehicle))

#this should result in true, because Car is a subclass of class Vehicle.

No comments:

Post a Comment