0%

Your First Classes and Objects · practice

Define a New Kind of Value

The previous lesson showed that an ordinary can use text where the program expects prompt. We repaired the key, but Python itself did not know what a complete quiz question should contain.

We now want to define a dependable kind of . You have already used many kinds of Python values: provide string operations, provide list operations, and each value has a type that tells Python what kind of it is.

A class is a definition Python can use to create objects of a new type. Here is the smallest useful class definition:

class Label:
    pass

class starts the definition. Label is the name of the new type. Class names normally use PascalCase, with each word beginning with a capital letter.

The indented body belongs to the class. pass is a placeholder that lets the body remain empty for the moment.

Create an instance

Once the definition exists, call the class:

label = Label()

This creates an object. We call an object created from a class an instance of that class.

These two names refer to different things:

  • Label refers to the class, which is the definition.

  • label refers to one instance created from that definition.

The distinction matters. A recipe is not a meal, and a class is not one of its instances. Unlike a recipe analogy, though, a Python class is executable code that Python uses directly.

A Label class definition creates one instance, and the variable label points to that object.

After this code runs, what does label refer to?

class Label:
    pass

label = Label()

An object can hold state

For this first example, we can attach attributes after creating the object:

label.text = "Question 1"
label.color = "blue"

An attribute is a named value belonging to an object. Dot notation connects the instance on the left with one of its attributes on the right.

Adding attributes afterward is enough to expose the basic pieces, but it is easy to forget one. Apply this syntax in the exercise by defining Question; the next lesson will then make sure every new question starts with both attributes.

Task

Define the Question class above the existing code.

Use pass as its body. The remaining code should create one instance, attach its prompt and answer attributes, and print the prompt.