Python Inheritance
Object-oriented programming makes it easy to write reusable code and avoid redundancy in development projects. One of the mechanisms by which object-oriented programming achieves this goal is the concept of inheritance, thanks to which a subclass can use the code for a base class that is also called a pre-existing "parent class".
What is heredity?
Inheritance is based on using the code of a certain class in another class, i.e. a class to be created inherits the code of another class. The concept of genetics in programming can be completely represented by genetics in biology. Sons inherit certain characteristics from their parents. A child can inherit his parent's height or eye color, as well as other new characteristics of his own. Children also share the same family name as their parents.
Subclasses, also called * child classes, inherit children and variables from * base classes (also called parent classes).
For example, we might have a base class called Parent that contains the variables of the classes last_name, height, and eye_color, which Child will inherit.
Since the child subclass inherits the Parent class, it can reuse the Parent code, allowing the programmer to write shorter code and reduce redundancy.
Basic varieties
Primary classes form the basis on which the subclasses can be based. Primary classes allow creating subclasses by inheritance without having to write the same code every time. Any class can be converted into a basic class, as it can be used on its own, or make it a template (template).
Suppose we have a base class named Bank_account, and two subclasses derived from it named Personal_account and Business_account. Like the withdrawal and deposit methods of funds, many of the methods will be shared between Personalaccount and Businessaccount, so these methods may belong to the base class Bank_account. The Business_account will have its own methods, such as the one dedicated to collecting business records and models, plus the employee_identification_number variable inherited from the parent.
Likewise, Animal may have the methods eating () and sleeping (), and the Snake subclass may have two additional methods named hissing () and slithering () of its own.
Let's create a base class named Fish to later use it as the basis for subclasses representing the fish species. Each of these fish will have first and last names, as well as their own distinct characteristics.
We'll create a new file called fish.py and start with the builder, in which we'll define the first_name and last_name class variables for all Fish objects, or its subclasses.
class fish:
def __init __ (self, first_name, last_name = "Fish"):
self.first_name = first_name
self.last_name = last_name
The default value for last_name is the string "Fish", because we know that most fish will have this last name.
Let's add some more methods:
class fish:
def __init __ (self, first_name, last_name = "Fish"):
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 all subclasses can use these methods.
Since most of the fish we intend to create will be bony (that is, they have a skeleton) and not cartilaginous (that is, they have a cartilaginous skeleton), we can add some additional properties to the __init __ () method:
class fish:
def __init __ (self, first_name, last_name = "Fish", skeleton = "bone", eyelids = False):
self.first_name = first_name
self.last_name = last_name
skeleton = skeleton
self.eyelids = eyelids
def swim (self):
print ("The fish is swimming.")
def swim_backwards (self):
print ("The fish can swim backwards.")
Building basic classes is not different from building any other class, except that we design them to take advantage of the subclasses defined later.
Subcategories
Subvarieties are varieties that inherit everything from the base variety. This means that subclasses are able to take advantage of the methods and variables of the base class.
For example, the Goldfish subclass, which is derived from the class Fish, will be able to use the swim () method defined in Fish without having to declare it.
We can think of subclasses as sections of the base class. If we have a subclass called Rhombus, and a basic class called Parallelogram, we can say that the Rhombus is a parallelogram.
The first line of a subclass looks a little different than a non-child class, since you must pass the base class to the subclass as a parameter:
class Trout (Fish):
Trout is a subspecies of Fish. This is indicated by the word "fish" in parentheses.
We can add new methods to the subclasses, or redefine the methods of the base class, or we can simply accept the default basic methods using the pass keyword, which we will do in the following example:
... class Trout (Fish): pass
We can now create a Trout object without requiring any additional methods to be defined.
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've created an object named terry from Trout, which will use all of the Fish and If we don't define it in the Trout subclass. It suffices to pass the value “Terry” to the variable first_name, the other variables are already configured.
When implementing the program, we will obtain the following outputs:
Terry Fish bone
False
The fish is swimming.
The fish can swim backward.
Now let's create another subclass that defines its method. We'll call this clownfish. Its dependent will allow coexisting with the marine anemones:
... class Clownfish (Fish):
def live_with_anemone (self):
print ("The clownfish is coexisting with sea anemone.")
Now let's create another Clownfish:
... casey = Clownfish ("Casey")
print (casey.first_name + "" + casey.last_name)
casey.swim ()
casey.live_with_anemone ()
When implementing the program, we will obtain the following outputs:
Casey Fish
The fish is swimming.
The clownfish is coexisting with sea anemones.
The output shows that the clownfish Casey is able to use the __init __ () and swim () methods of Fish, in addition to the live_with_anemone () method of the subclass.
If we try to use the live_with_anemone () method in the Trout object, an error will be thrown:
terry.live_with_anemone () AttributeError: 'Trout' object has no attribute 'live_with_anemone'
The live_with_anemone () method belongs to the Clownfish subclass only, not to the main class Fish.
Subclasses inherit the methods of the base class from which they are derived, so all subclasses can use those methods.