Python: How to set default value for a attribute in child class

Viewed 1501

I am working on Python and I have defined a Parent class as follows

class Country:
    """Models countries"""
    def __init__(self, name, population, continent, zone):
        """Initiates the Country class"""
        self.na = name
        self.co = continent
        self.zo = zone
        self.po = population

I have also defined two method in this class. I have created a subclass named Europe_country in which I want to set default value of continent and zone to 'Europe' and 'Temperate' respectively.

I have tried to do it like this

class Europe_country(Country):
    """Models European countries specifically"""
    co = 'Europe'
    zo = 'Temperate'

europe_1 = Europe_country('Abc', 999)

But obviously I am wrong. I am unable to find a solution for this problem on the internet. Please help.

3 Answers

I would do something like this:

class Country:
    """Models countries"""
    def __init__(self, name, population, continent, zone):
        """Initiates the Country class"""
        self.na = name
        self.co = continent
        self.zo = zone
        self.po = population
        
class Europe_country(Country):
    """Models European countries specifically"""
    def __init__(self, name, population):
        super().__init__(name, population, "Europe", "Temperate")

europe_1 = Europe_country('Abc', 999)

Call the parent constructor with predefined values and set the rest from the child constructor.

your subclass only accepts 2 inputs, so you need to overwrite the __init__ of the parent class to accept only 2 inputs, you can then invoke the init of the parent class passing your two inputs and your set values.

class Country:
    """Models countries"""

    def __init__(self, name, population, continent, zone):
        """Initiates the Country class"""
        self.na = name
        self.co = continent
        self.zo = zone
        self.po = population

class Europe_country(Country):
    """Models European countries specifically"""
    co = 'Europe'
    zo = 'Temperate'

    def __init__(self, name, population):
        super().__init__(name, population, self.co, self.zo)

europe_1 = Europe_country('Abc', 999)

Just use super to force the initalization of the base class while taking 2 other parameters in the child class:

class Europe_country(Country):
    """Models European countries specifically"""
    def __init__(name, population):
        super().__init__(name, population, "Europe", "Temperate")
Related