- Extend a Class in Python
- Extend a Class in Python
- Extend a Class Using Inheritance in Python
- Add the __init__() Function to the Child Class After Extending a Class
- Use the super() Function After Extending a Class in Python
- Add Attributes to the Child Class After Extending a Class in Python
- Add Methods to the Child Class After Extending a Class in Python
- Related Article — Python Class
- How to Extend Classes to Make New Classes in Python
- Building the child class
- Testing the class in an application
- About This Article
- This article is from the book:
Extend a Class in Python
In Python, we can extend a class to create a new class from the existing one. This becomes possible because Python supports the feature of inheritance.
Using inheritance, we can make a child class with all the parent class’s features and methods. We can also add new features to the child class other than those present in the parent class.
We can even override those features of the parent class that we don’t need. You will learn how to do all that as you go through this article.
Extend a Class in Python
In simple terms, extending a class means that we want to create a new class or child class from an existing or parent class. Extending a class is the same as inheriting a class.
Let us see how inheritance works in Python.
Extend a Class Using Inheritance in Python
To inherit a class in Python, we pass the name of that class as a parameter while creating the child class.
class ChildClass(ParentClass)
Let us understand this with an example.
We first create a parent class, Desserts , with two methods — init and intro . The method intro has a print statement that prints the flavor and color shown in the output.
class Desserts: def __init__(self, flavor, color): self.flavor = flavor self.color = color def intro(self): print(self.flavor, self.color) obj = Desserts("Vanilla", "Pink") obj.intro()
We create the child class, Cake that will inherit the class, Desserts . For the Cake class to inherit the Desserts class, we will pass the name of the Desserts class as a parameter while creating the Cake class.
We are using the pass keyword here because we are only inheriting the class, Desserts , and not adding any other method or feature to the child class, Cake . The cake class now has the same attributes and methods as the Desserts class.
We can verify this by creating an object of the Cake class and then executing the intro method as shown in the last two lines of code.
class Desserts: def __init__(self, flavor, color): self.flavor = flavor self.color = color def intro(self): print(self.flavor, self.color) obj = Desserts("Vanilla", "Pink") obj.intro() class Cake(Desserts): pass obj = Cake("Black forest", "Black") obj.intro()
Vanilla Pink Black forest Black
See how the Cake class also executes the intro method like the Desserts class.
Let us see how we can add more methods and attributes to this newly created child class.
Add the __init__() Function to the Child Class After Extending a Class
We can add a new init() function to the child class even when inheriting a class. Note that whenever an object of a class is created, the init() function is automatically called.
Also, adding the init() function to the child class will not use the parent class’s init() function.
class Cake(Desserts): def __init__(self, flavor, color): self.flavor = flavor self.color = color
Although the init() method of the child class overrides the inheritance of the init() method of the parent class, we can still use the parent’s init() method by calling it like this:
class Cake(Desserts): def __init__(self, flavor, color): Desserts.__init__(self, flavor, color)
Use the super() Function After Extending a Class in Python
In Python, the super() function can be used to access the attributes and methods of a parent class.
When there is a new init() inside a child class that is using the parent’s init() method, then we can use the super() function to inherit all the methods and the properties from the parent class.
class Cake(Desserts): def __init__(self, flavor, color): super().__init__(flavor, color)
Note that here, we are not specifying the name of the parent class; the super() function automatically identifies it.
This was all about the basics of inheritance in Python.
But what if we have to add more attributes or methods to the child class? Let us see how we can do that.
Add Attributes to the Child Class After Extending a Class in Python
We can add extra attributes to a child class other than those inherited by the parent class just like we add any other attribute. See how a property called quantity is added to the Cake class.
class Cake(Desserts): def __init__(self, flavor, color, quantity): super().__init__(flavor, color) self.quantity = quantity
We added one more parameter in the child class’s init() function. Also, do not forget to pass one more value for quantity while creating the object of the Cake class, like this:
obj = Cake("Black forest", "Black", 5)
Add Methods to the Child Class After Extending a Class in Python
We add a method price in the child class by simply using the def keyword in the code below. We also pass the self keyword as the parameter.
class Cake(Desserts): def __init__(self, flavor, color, quantity): super().__init__(flavor, color) self.quantity = quantity def price(self): print("Pay for: ", self.quantity, "items.")
The entire code would be as follows:
class Desserts: def __init__(self, flavor, color): self.flavor = flavor self.color = color def intro(self): print(self.flavor, self.color) obj = Desserts("Vanilla", "Pink") obj.intro() class Cake(Desserts): def __init__(self, flavor, color, quantity): super().__init__(flavor, color) self.quantity = quantity def price(self): print("Pay for: ", self.quantity, "items") obj = Cake("Black forest", "Black", 5) obj.intro() obj.price()
Vanilla Pink Black forest Black Pay for: 5 items
Note that adding a method with the same name as any method in the parent class will override the inherited method.
This is how we can extend a class in Python. Refer to this official documentation to learn more.
Related Article — Python Class
Copyright © 2023. All right reserved
How to Extend Classes to Make New Classes in Python
As you might imagine, creating a fully functional, production-grade class in Python (one that is used in a real-world application actually running on a system that is accessed by users) is time consuming because real classes perform a lot of tasks. Fortunately, Python supports a feature called inheritance. By using inheritance, you can obtain the features you want from a parent class when creating a child class.
Overriding the features that you don’t need and adding new features lets you create new classes relatively fast and with a lot less effort on your part. In addition, because the parent code is already tested, you don’t have to put quite as much effort into ensuring that your new class works as expected.
The following sections show how to build and use classes that inherit from each other.
Building the child class
Parent classes are normally supersets of something. For example, you might create a parent class named Car and then create child classes of various car types around it.
In this case, you build a parent class named Animal and use it to define a child class named Chicken . Of course, you can easily add other child classes after you have Animal in place, such as a Gorilla class. However, for this example, you build just the one parent and one child class.
class Animal: def __init__(self, Name=", Age=0, Type="): self.Name = Name self.Age = Age self.Type = Type def GetName(self): return self.Name def SetName(self, Name): self.Name = Name def GetAge(self): return self.Age def SetAge(self, Age): self.Age = Age def GetType(self): return self.Type def SetType(self, Type): self.Type = Type def __str__(self): return " is a aged ".format(self.Name, self.Type, self.Age) class Chicken(Animal): def __init__(self, Name=", Age=0): self.Name = Name self.Age = Age self.Type = "Chicken" def SetType(self, Type): print("Sorry, will always be a " .format(self.Name, self.Type)) def MakeSound(self): print(" says Cluck, Cluck, Cluck!".format(self.Name))
The Animal class tracks three characteristics: Name , Age , and Type . A production application would probably track more characteristics, but these characteristics do everything needed for this example. The code also includes the required accessors for each of the characteristics. The __str__() method completes the picture by printing a simple message stating the animal characteristics.
The Chicken class inherits from the Animal class. Notice the use of Animal in parentheses after the Chicken class name. This addition tells Python that Chicken is a kind of Animal , something that will inherit the characteristics of Animal .
Notice that the Chicken constructor accepts only Name and Age . The user doesn’t have to supply a Type value because you already know that it’s a chicken. This new constructor overrides the Animal constructor. The three attributes are still in place, but Type is supplied directly in the Chicken constructor.
Someone might try something funny, such as setting her chicken up as a gorilla. With this in mind, the Chicken class also overrides the SetType() setter. If someone tries to change the Chicken type, that user gets a message rather than the attempted change. Normally, you handle this sort of problem by using an exception, but the message works better for this example by making the coding technique clearer.
Finally, the Chicken class adds a new feature, MakeSound() . Whenever someone wants to hear the sound a chicken makes, he can call MakeSound() to at least see it printed on the screen.
Testing the class in an application
- Open a Python File window. You see an editor in which you can type the example code.
- Type the following code into the window — pressing Enter after each line:
import Animals MyChicken = Animals.Chicken("Sally", 2) print(MyChicken) MyChicken.SetAge(MyChicken.GetAge() + 1) print(MyChicken) MyChicken.SetType("Gorilla") print(MyChicken) MyChicken.MakeSound()