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) # WoofHere 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) # BuddyEach object is independent. Setting buddy.name does not touch any other Dog.
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".
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.