Discord Server Red Security Twitter Donation to Red Security Red Security Youtube Channel Red Security Tumblr Profile
Login or Register to Hide ads and Accessing all features on the forum

Tutorial 

Python 3.2: Inheritance in Python

2 Replies, 2802 Views

[Image: BFMMlbcQvml9HSqXcvNp]
Inheritance:
               Hi guys, I hope you all are doing well. In today's thread We are going to jump deep into python OOP. So first of all let’s see how we can make two or more classes in one program and make relations between them. Let's create a program in which we create two classes and show you how these classes can interact with each other. 

Code:
class Student:
    def __init__(self, name, age, marks):
        self.name = name
        self.age = age
        self.marks = marks
    def get_marks(self):
        return self.marks
class Course:
    def __init__(self, name, student_num):
        self.name = name
        self.student_num = student_num
        self.students = []
    def add_student(self, student):
        if len(self.students) < self.student_num:
            self.students.append(student)
            return True
        return False

    def avg_marks(self):
        avg = 0
        for student in self.students:
            avg += student.get_marks()
        return avg/len(self.students)


s1 = Student("Covid", 19, 78)
s2 = Student("Kurd", 19, 76)
s3 = Student("JJAskis", 19, 56)

c1 = Course("Python", 3)

c1.add_student(s1)
c1.add_student(s2)
print(c1.students[0].name)
print(c1.students[1].name)

print(c1.avg_marks())


So as in this program we have two classes and we show you how these classes interact with each other. The Student class has only one method while the Course class has two methods. In the first method we have created a list of students and this list is empty initially but the first method will add students to it. This will also check for an empty index in the list if the list is not free it will return false.

As now you know that we can use two classes in one program but wait in some classes we have similarities like the class of Iphone and a class for Samsung has similarities. Similarly a class for cats has similarities with a class of dogs. In other words, Inheritance is used for "is-a" relationships. Example, the Base/Super class is Animal: Derived Class / Subclass: ● Cat ● Dog Cat 'is an' Animal. Dog 'is an' Animal.

So now let’s have a look at the code that how we can create a program for inheritance

Code:
#superclass
class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
#cat class
class Cat(Animal):
    def purr(self):
        print("Purr...")
#Dog class       
class Dog(Animal):
    def bark(self):
        print("Woof!")
#Dog instance
jemsi = Dog("Jemsi", "brown")
print(jemsi.name)
print(jemsi.color)
jemsi.bark()

print("_____________")

#cat instance

koko=Cat("Koko","gray")
print(koko.name)
print(koko.color)
koko.purr()



Here we created one superclass that is Animal and two subclasses of that superclass one is Cat and other one Dog. Both animals have names and color of their body. But the functions of both are changed so we have created a superclass and now we can create as many subclasses as we want. Subclasses always inherit properties of superclasses. What happens if we have a superclass and a subclass with similar attributes and methods? The Answer is simple the subclass will override superclass look at this example below,,,

Code:
class Mobile:
    def __init__(self, name , model):
        self.name = name
        self.model = model
    def func(self):
        print('Surfing internet and calling...')

class Iphone(Mobile):
    def __init__(self, name , model):
        self.name = name
        self.model = model
    def func(self):
        print('Surfing internet, Calling with Best Camera...')

######## This is not promotion of Iphone ###########


my_mobile = Iphone("12" ,"Pro Max")

my_mobile.func()


In this example both the classes have similar attributes and methods. When we call this method of func() this will override the superclass’s func() method. Hope you got the point

The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

Now, Let’s discuss another function of inheritance that is super() Function
Like in other object-oriented languages, it allows you to call methods of the superclass in your subclass. The primary use case of this is to extend the functionality of the inherited method. Let’s see an example of this function

Code:
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def eat(self):
        print("Eats depends")

class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name,age)
        self.breed = breed

    def eat(self):
        print("Eats meat")
class Goat(Animal):
    def __init__(self, name, age, height):
        super().__init__(name,age)
        self.height = height

    def eat(self):
        print("Eats hay, grasses, weeds, grain ")

jemsi = Dog("Jemsi", 10, 'Husky')
print(jemsi.breed)
jemsi.eat()

kola = Goat("Kola", 3, 7)
print(kola.age)
kola.eat()


So as you can see in this function the name and age attributes are present in animal class which is a superclass and we are using super() function to call these attributes to our subclasses.
That’s it for now. I hope you have understood each and every concept in this thread, if you don’t then you can ask me anytime in discord or ask your question in reply. Thank you,,,

"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"
Love me like you do Heart
Thanks Man for explaining in detail. This inheritances is really saving time if you take advantage of it. But I never put effort or use in it.. Not sure why tho ...
Rs
* Thankful to Allah *
Kurdy
(05-25-2022, 11:52 AM)Mr.Kurd Wrote: Thanks Man for explaining in detail. This inheritances is really saving time if you take advantage of it. But I never put effort or use in it.. Not sure why tho ...

Your Welcome bruh  Heart
Love me like you do Heart

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tutorial Doubly Linked List in Python Covid-19 0 2,227 07-30-2022, 09:15 PM
Last Post: Covid-19
  Tutorial Linked List in Python Covid-19 2 2,607 07-30-2022, 08:25 PM
Last Post: Covid-19
  Tutorial File Handling in Python Covid-19 2 2,645 06-16-2022, 06:17 PM
Last Post: Covid-19
  Tutorial Exceptions in Python Covid-19 0 1,825 06-08-2022, 09:19 PM
Last Post: Covid-19
  Free Automate the boring stuff with Python Covid-19 0 1,591 06-07-2022, 06:58 PM
Last Post: Covid-19
  Tutorial Turtle in Python Covid-19 0 1,823 06-02-2022, 10:14 PM
Last Post: Covid-19
  Tutorial Python 3.5: Class Methods Covid-19 0 1,772 05-29-2022, 01:07 PM
Last Post: Covid-19
  Tutorial Python 3.4: Encapsulation and Abstraction Covid-19 0 1,804 05-27-2022, 06:45 PM
Last Post: Covid-19
  Tutorial Python 3.3: Operator Overloading Covid-19 2 2,799 05-26-2022, 08:50 PM
Last Post: Covid-19
  Tutorial Python 3.1: OOP Covid-19 2 1,627 05-24-2022, 06:37 PM
Last Post: Covid-19



Users browsing this thread: 1 Guest(s)