Module 7 - Section 1 - Classes
Module 7 - Section 1 - Classes
- identify a class inside Python code
- present the necessary parts for constructing a class
- create code to construct a simple class
- create and use methods in a class
- distinguish the references from the objects of a class
- rewrite the classes code to implement constructors
7.1.2 - Create a Class
To create a Class we can define it, in the same way as a function. Class names always start with a capital letter unlike functions. While it is possible to begin a class with a lower case letter, it is not considered good practice.
Copy the above code to Thonny's Script Area and save it as animals in your projects folder.
class Animal():
""" This is a class that represents animals in a game. """
def __init__(self):
""" Set up the animals fields. """
self.name = ""
self.type = ""
self.color = ""
self.legs = ""
self.speed = ""
The def __init__(self) is a special function called a constructor that is run automatically when the class is created.
The self. is kind of like the pronoun my. When inside the class Animal we are talking about my name, my type, my color, etc.
Inside the Script Area of Thonny add the following code after line 10 taking care of indentation.
# Create an animal
shawn = Animal()
#shawn's attributes
shawn.name="Shawn"
shawn.type="sheep"
shawn.color="white"
shawn.legs=4
shawn.speed=50
# Create another animal
kitty = Animal()
#kitty's attributes
kitty.name="Kitty"
kitty.type="cat"
kitty.color="orange"
kitty.legs=4
kitty.speed=24
With the above code, after creating the class Animal, we have created two instances of class animals, a sheep and a cat. Those two instances are called objects. A simple definition is that an object it is an instance of a class.
To visualize the execution of this code click here (www.pythontutor.com)