Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstration of python classes and inheritance.
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
class Dog(Pet):
def __init__(self, name, chases_cats):
Pet.__init__(self, name, "Dog")
self.chases_cats = chases_cats
def chasesCats(self):
return self.chases_cats
class Cat(Pet):
def __init__(self, name, hates_dogs):
Pet.__init__(self, name, "Cat")
self.hates_dogs = hates_dogs
def hatesDogs(self):
return self.hates_dogs
@francisgan9

This comment has been minimized.

Copy link

commented Mar 25, 2014

THANKS A LOT

@cristihainic

This comment has been minimized.

Copy link

commented May 7, 2015

many thanks for your tutorial. I found it to be the best so far that explains class inheritance.

@WindBlade

This comment has been minimized.

Copy link

commented Sep 28, 2015

Great tutorial!

@frjaraur

This comment has been minimized.

Copy link

commented Nov 22, 2015

Many Thanks for this sort example :)

@aKD12345

This comment has been minimized.

Copy link

commented Mar 18, 2016

Really nice documentation on class inheritance

@Tejaf

This comment has been minimized.

Copy link

commented Sep 7, 2016

Thank you very much for the explanation. i have a question please. if i have something like this:
class Pet(object):

def __init__(self, name, specie):
    self.name = name
    self.specie = specie

def get_name(self):
    return self.name

def get_specie(self):
    return self.specie

def __str__(self):
    return '{} is a {}'.format(self.name, self.specie)

class Dog(Pet):

def __init__(self, name, color):
    Pet.__init__(self, name, 'Dog')
    self.color = color

def color(self):
    return self.color

EOF

what if i want the class Dog to print out name is a color dog inheriting from method str of class Pet. is it possible?
if yes, how? thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.