A Virtual Dog Example

From Knowledge Kitchen
Jump to navigation Jump to search


A virtual dog that can fetch, roll over, sleep, wake up, and even speak. Written in Python.

A few things to note:

  • documentation: the use of docstrings to describe the file, the class, and each function
  • documentation: the use of comments in a few places to help explain the code
  • validation: the way the set_age function checks to make sure the age is valid before setting it
  • validation: the way the roll_over function checks to make sure the dog is not sleeping rolling over
  • strings: the use of Python's built-in format() function to insert variables into strings
  • strings: the use of the title() function to nicely capitalize the name of each dog
  • data types: the various data types being used: strings, integers, and booleans
  • the use of if/else conditionals to decide what to do at various times
  • the use of functions to make the code "modular"
  • see the virtual cat example for an extension of these same concepts


The Dog class

Save this code into a file named dog.py. You will not execute (i.e. "run") this code. Rather, this code will be used by other test scripts which will be executed.

"""
This file contains the Dog class, which is like the mold from which Dogs are made.
You can make individual Dog objects from this Dog class.
"""

class Dog:
    """A dog with a name and age that can respond to the following commands:
        fetch
        roll_over
        sleep
        wake_up
        speak
    """

    def __init__(self, name="Spot", age=0):
        """This initialization function is automatically called when a new Dog object is created

        Keyword arguments:
            name -- the desired name, as a string (default: "Spot")
            age -- the desired age, as an integer (default: 0)
        """
        print("Another dog is born...")
        self.wake_up()                  #our dog starts off life awake
        self.set_name(name.title())     #set the name of the dog
        self.set_age(age)               #set the age of the dog
    
    def set_name(self, some_word):
        """Setter function for the name property

        Keyword arguments:
            some_word -- the desired name, as a string
        """
        self.name = some_word           #set the name of this dog
        self.speak("Hello, my name is {}!".format(self.name))

    def set_age(self, some_number):
        """Setter function for the age property

        Keyword arguments:
            some_number -- the desired age, as an integer
        """
        if some_number >= 0 and some_number <= 16:
            self.age = some_number      #set the age of this dog
            self.speak("My age is {}.".format(self.age))
        else:
            self.speak("Sorry... that's an unreasonable age for a dog like me.")

    def roll_over(self):
        """Make the dog roll over, if it's not sleeping"""
        if not self.sleeping == True:
            self.speak("Rolling over!")
        else:
            self.speak("Sorry...  I'm sleeping and don't want to roll over right now.")

    def go_to_sleep(self):
        """Make the dog go to sleep.. this is a setter function for the sleeping property"""
        self.sleeping = True            #set the sleeping attribute to be True, meaning the dog is asleep
        self.speak("Zzzzzzzz...")

    def wake_up(self):
        """Make the dog go wake up... this is another setter function for the sleeping property"""
        self.sleeping = False           #set the sleeping attribute to be False, meaning the Dog is awake
        self.speak("Woof!")

    def speak(self, phrase):
        """Tell the dog to say something in the third person

        Keyword arguments:
            phrase -- the phrase to speak, as a string
        """
        if hasattr(self, 'name'):
            print("{} says, '{}'".format(self.name, phrase))
        else:
            print("An unnamed dog says, '{}".format(phrase))

Test programs

Two scripts you can use to "test" the Dog class by creating some dog objects and instructing them to perform various tricks. These are the scripts you will actually want to execute.

Make one dog

Save this code into a file named make_one_dog.py:

"""This script creates one Dog object from the Dog class and instructs that dog to perform some tricks"""

#load all the code from the dog.py file 
from dog import *

#make a new Dog object, with the name "Spot" and the age 10
spot = Dog("spot", 10)

#tell the dog to roll over
spot.roll_over()

#tell the dog to go to sleep
spot.go_to_sleep()

#tell the dog to roll over... it won't do it because it's sleeping!
spot.roll_over()

#tell the dog to wake up
spot.wake_up()

#tell the dog to roll over... it will do it this time since it's awake!
spot.roll_over()

Make two dogs

Save this code into a file named make_two_dogs.py:

"""This script creates two Dog objects from the Dog class and instructs each dog to perform some tricks"""

#load all the code from the dog.py file 
from dog import *

#make two new Dog objects with different names and ages
spot = Dog("spot", 10)
fido = Dog("fido", 2)

#tell each dog to roll over
spot.roll_over()
fido.roll_over()

#tell Spot to go to sleep
spot.go_to_sleep()

#tell each dog to roll over... Spot won't do it because it's sleeping, but Fido will because it's awake!
spot.roll_over()
fido.roll_over()

#tell Spot to wake up, but Fido to go to sleep
spot.wake_up()
fido.go_to_sleep()

#tell each dog to roll over... Spot will do it this time since it's awake, but Fido won't!
spot.roll_over()
fido.roll_over()


What links here