Firearrow5235
Firearrow5235

Reputation: 296

Python subclass uses parent variables in constructor

So I'm working on a Text Based RPG and I have a class Item which looks like this:

class Item:
    def __init__(self, name, value):
        self.name = name
        self.value = value

Next I have a weapon class which I want to have inherit from the item class, and in the weapon constructor I want it to take the "name" and "value" variables. In my head it works like this:

class Weapon(Item):
    def __init(self, name, value, damage):
        self.damage = damage

Which I know is wrong, but that's essentially how I think it should work. I've looked up a bunch of threads on the "super()" function, but none of the explanations seem to be doing this. So is this something that's possible or should I just make the weapon class separate? Also... when it does work... what would the constructor call look like?

Upvotes: 2

Views: 1799

Answers (2)

Michael Rose
Michael Rose

Reputation: 7820

You can use it as follows inside your Weapon class:

class Weapon(Item):
    def __init__(self, name, value, damage):
        super(Weapon, self).__init__(name, value)
        self.damage = damage

And be sure to use new-style classes, i.e. inherit from object:

class Item(object):
    ...

Upvotes: 3

bdesham
bdesham

Reputation: 16089

Yes, calling the parent class’s constructor is something that you usually need to do:

class Weapon(Item):
    def __init__(self, name, value, damage):
        # Initialize the Item part
        Item.__init__(self, name, value)

        # Initialize the Weapon-specific part
        self.damage = damage

As for making the weapon class separate—you should read through the article on composition over inheritance. People have varying opinions on whether inheritance is “right” and in which situations. Sorry that’s so vague, but you haven’t given that much information about your use case :-)

Upvotes: 0

Related Questions