Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Python, attribute inheritance works through the use of the "init" method. This method is called when a new instance of a class is created, and it initializes the instance's attributes.

When a subclass is created, it inherits all the attributes of its superclass. This means that when an instance of the subclass is created, the "init" method of the subclass is called, which in turn calls the "init" method of the superclass to initialize its attributes.

If the subclass needs to add new attributes, it can do so in its own "init" method. This method should first call the "init" method of the superclass to initialize its inherited attributes, and then define any new attributes as needed.

For example, suppose we have a superclass "Animal" with an attribute "species", and a subclass "Cat" that adds a new attribute "name". The code might look like this:

class Animal:
    def __init__(self, species):
        self.species = species

class Cat(Animal):
    def __init__(self, name, species):
        super().__init__(species)
        self.name = name

In this example, when we create a new instance of "Cat", its "init" method is called. This method first calls the "init" method of the superclass "Animal" to initialize the "species" attribute, and then initializes the new "name" attribute.

By calling the superclass's "init" method first, the subclass ensures that all inherited attributes are properly initialized.