Syllabus Lesson 47 of 239 · Object-Oriented Python
Object-Oriented Python

Classes and Objects

So far your data and your functions have lived apart. A class lets you bundle them together. Think of a class as a blueprint, and an object (also called an instance) as one thing built from that blueprint.

You define a class with the class keyword. Class names use CamelCase by convention.

class Dog:
    sound = "Woof"

rex = Dog()
print(rex.sound)   # Woof

Here Dog is the blueprint and rex is one object made from it. We reach inside an object with a dot: rex.sound. That sound is an attribute, a piece of data attached to the object.

You can build many objects from one class, and you can give each one its own attributes after creating it:

buddy = Dog()
buddy.name = "Buddy"
print(buddy.name)   # Buddy

Each object is independent. Setting buddy.name does not touch any other Dog.

Your turn

Define a class called Car with a class attribute wheels set to 4. Then create one instance, store it in a variable called my_car, and give that instance an attribute color set to "red".

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output