Python: Inheriting Methods From A Parent Class

Recently I’ve been working on a refactor of my PyPet Game.  I wrote the original code a long time ago, and didn’t understand Sub-classing* super well.  I understand the mechanics a lot better now.  Except I got stumped on trying to take the Method from the parent class.

Stack Overflow – Call a Parent Class Method from Child Class in Python


*To get the gyst of subclassing:  In my PyPet game I have 5 different pet types (Cat, Rat, Mouse, Bunny, Turtle).  Those Pets all have some common attributes (name, hungry, starved, bored, upset, violent, sleepy, awake/asleep) & common methods**  to output messages (like “I’m hungry” or “Pay attention to me”).

If I were to write these as 5 separate classes, I’d have to write all these attributes & functions for each Pet.  That’s a lot of unnecessary repetition.

Instead, I can write a Parent Class “Pet” & have each Child Class inherit from it.  It would look something like this:

class Pet(object):
    def __init__(self):
        self.hungry = True
        self.sleepy = False

        self.messages= {
        'hungry': "I'm hungry"
        'sleepy': "*Yawn* - I'm so tired"
        }

    def message_output(self, key):
        self.key = key
        print(self.message[self.key])


class Cat(Pet):
    def __init__(self):
        self.key = key

    def message_output(self, key):
        # Inherit method from Pet (Parent Class) here

And I could do that for each pet type. Which would save me a lot of lines of code!

**Method: A Method is a function I can call on an instantiated class.  For Example:

Pet.message_output() or Cat.message_output()

Coming Soon: In the future, I’m planning to write a set of Tutorials called “A Friendly Introduction to Object-Oriented Programming (aka Classes) in Python using Cats & Dogs” – I’ll be sure to post it here when I do!

Advertisements
Python: Inheriting Methods From A Parent Class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s