Tuesday, 3 March 2020

Python Inheritance

Python Inheritance

If we have a basic Student class which we want to modify to create a University Student object, we can create a new class that incorporates the methods and variables in the Student class but adds new features such as the name of the University. 

Student class is referred o as the parent class while University Student class is called the child class. We say that UniversityClass is inheriting from Student class.

The Unified Modeling Language (UML) is a set of diagrams that allows you to represent many types of relationship. One type of UML diagram is called a Class Diagram and is used to represent relationships between classes. An example is shown:


To specify the visibility of a class method use the following prefixes:
+Public
-Private
#Protected
~Package
Different types of arrows have the following meanings:
The one in the example diagram above means that UniversityStudent inherits from Student. All non-private methods in Student can be directly accessed in UniversityStudent. If the method in UniversityStudent has the same name as that in Student, we call this situation, method overriding. 




Python Constructors (def __init__)

Python Constructors (def __init__)

In Object-Oriented Programing, a constructor is used to initialise object variables when we create a new object based on a given class. If we had a class called  Student with variables Name, Phone, Email, each time we create a new Student object, we need to supply the values of Name, Phone and Email.

In Python, we would create such a class as follows:

class Student:
    def __init__(self, name, phone, email):
        self.name = name
        self.phone= phone
        self.email= email
        # return statement removed from here
We can create a Student object as follows:

s1=Student("Genghis Khan", "+123456789","Genghis.Khan@gmail.com")
We can acess the object variables of the Student called s1 as follows:
print(s1.name)
print(s1.phone)
print(s1.email)
In IDLE, the program looks as follows:
Output:
The keyword "self" refers to the object we have created. 
Sometimes we have default values for the constructor variables.