Inheritance

Inheritance is a way through which we create hierarchies in the objects, going from the most general to the most specific. A class that usually forms the base for another class is also known as a base class, whereas a class that inherits from a base class is known as a child class. For example, if a class B derives from class A, then we will say that class B is a child class of class A.

Just like C++, Python supports the concept of both multiple and multilevel inheritance, but does not support the use of access modifiers while inheriting in a class that C++ supports.

Let's take a look at how inheritance can be achieved in Python by trying to model how a new request will look in our BugZot application. The following snippet gives us a small example about the concept of inheritance:

class Request:
def __init__(self, title, description, is_private=False):
self.title = title
self.description = description
self.is_private = is_private

def get_request():
request_data = {
'title': self.title,
'description': self.description,
'is_private': self.is_private
}
return request_data

class Bug(Request):
def __init__(self, title, description, affected_release, severity, is_private):
self.affected_release = affected_release
self.severity = severity
super().__init__(title, description, is_private)

def get_bug():
bug_data = {
'title': self.title,
'description': self.description,
'severity': self.severity,
'affected_release': self.affected_release,
'is_private': self.is_private}
return bug_data

As we can see from the example, we just used inheritance while creating the Bug class by making the Bug class derived from the request class. In OOP terminology, the Bug class will be called the child of the Request class. When an object of the Bug class is created, it calls the constructor of the Bug class, followed by the constructor of the Request class.

In Python, all the classes inherit from the object class:

req = Request('Missing access modifier support in class inheritance', 'We are lacking the support for using access modifiers in class inheritance', False)
isinstance(req, object)
>>> True
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194