Sign InCoursewareNuggetsTutorials AboutClassesCodePad

Objects and Classes

Do you remember the computational thinking process? When solving a complex problem, we need to break it down to more tractable problems, identify patterns, and focus on the important aspects. We have learned to use functions to define repeated procedures to be used over and over again. In some situations, it is more appropriate to group information around data, not procedures.

Getting Classy

In the real world, we are surrounded by things -- animals, houses, cars -- you name it. We can describe these things with a set of attributes and behaviors. For example, attributes of a dog may include its breed, age, and color. For its behaviors, a dog can run, jump and bark. Things of the same kind share many common traits.

Similarly, in Python we can use "objects" to represent "things." An object contains a set of variables to describe its attributes and a set of functions to describe its behaviors. Objects of the same kind share many common traits. We use "classes" to classify these common traits.

One Classe, Many Objects

In fact, you've already used classes and objects before. Take turtle graphics, for example. The "things" we use in our program are the turtle objects. Common traits of the turtle objects are defined by the Turtle class. When we call kelly = turtle.Turtle(), we create a turtle object and give it a name "kelly." A turtle's attributes may consist of position, speed, color, etc. We can control kelly's behaviors through functions such as forward( ), backward( ) or circle( ). The following program creates two turtle objects kelly and jack. We can clearly see that the two turtles maintain their own attributes, including position, color, and shape. They change and move separately by the same set of functions shape( ), color( ), and forward( ).

import turtle turtle.Screen().setup(800,80) kelly = turtle.Turtle() kelly.color("red") kelly.shape("turtle") kelly.backward(200) jack = turtle.Turtle() jack.color("blue") jack.shape("classic") jack.forward(100)

© CS Wonders·About·Classes·Cheatsheet