Classes and inheritance in Python

This example is similar to the Inheritance in PHP snippet. Python is used instead of PHP.

#!/usr/bin/env python

# Define the Person class
class Person:
    # Define the constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def Walk(self):
        return 'Person: Walking!'

# Inheritance
class PizzaDeliveryGuy(Person):
    # Override the Walk method
    def Walk(self):
        return 'PizzaDeliveryGuy: Walking!'
    def DeliverPizza(self):
        return 'Have a nice day!'

# Create an instance of Person
personInstance = Person("Santa",191)

# Create an instance of PizzaDeliveryGuy
pizzaDeliveryGuyInstance = PizzaDeliveryGuy("Luigi",30)

# Print the Person instance
print 'Name: ' + personInstance.name
print 'Age: ' + str(personInstance.age)
print personInstance.Walk()

print ''

# Print the PizzaDeliveryGuy instance
print 'Name: ' + pizzaDeliveryGuyInstance.name
print 'Age: ' + str(pizzaDeliveryGuyInstance.age)
print pizzaDeliveryGuyInstance.Walk()
print pizzaDeliveryGuyInstance.DeliverPizza()

Output:

Name: Santa
Age: 191
Person: Walking!

Name: Luigi
Age: 30
PizzaDeliveryGuy: Walking!
Have a nice day!
This entry was posted in Python and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?