Module 7 - Section 1 - Classes

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 = ""

In the code above, Animal is the class name. The variables in the class, such as name, type, color, legs and speed are called attributes or fields.

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) 

animals class

class