Home > database >  Simple question on how to create subclasses?
Simple question on how to create subclasses?

Time:04-13

I'm new to the idea of object-oriented programming in Python, and the school has given me a question to first create a class called "Mammal", with an attribute "name" and method get_name(). Hence I came up with this:

class Mammal(object):
    def __init__(self, name):
        self.name = name
        
    def get_name(self):
        return self.name

Seems alright. The next part of the question asks me to create a subclass Dog which has the name dog and the same method. Out of inheritance from the superclass, I created:

class Dog(Mammal):
    def __init__(self,name):
        super().__init__(name)

I am given the test case Dog().get_name(), to which the output should be Dog, but I keep receiving an error TypeError: __init__() missing 1 required positional argument: 'name'.I have then tried amending the third line of the second code to

class Dog(Mammal):
    def __init__(self,name):
        super().__init__(Dog)

but the error remains. I have searched online how to do inheritance from a superclass and it seems that my code structure is correct, but I simply cannot pass the name "Dog" into the class to make get_name() work.

Can someone point out what is wrong with this to me? Any help is greatly appreciated!

CodePudding user response:

First example

You are specifying to enter a name to construct your Dog subclass

class Dog(Mammal):
    def __init__(self,name):   # <--- name parameter
        super().__init__(Dog)

so if you want to create an instance of your subclass you have to provide a name (Implied of type string). To do that, you'll have to construct an instance like that:

Dog("Berry").get_name()

This code will then return the string "Berry", which is the name you have specified in the constructor.

Second example

class Dog(Mammal):
    def __init__(self,name):   # <--- name is unused, so it can be removed
        super().__init__(Dog)

You call the parent constructor with your subclass Dog, so if you do get_name() on that instance, it won't return the string "Dog", but it will return the Dog subclass.

Keep in mind that python is really dynamic and won't throw errors immediately if types aren't correct, hence it is interpreted. I recommend you to read more about how classes work in general to get a better understanding of the common principles and how it can be beneficial in your code.

  • Related