Python Classes & Objects
A class is a blueprint that describes a kind of thing. An object is one thing built from a class.
Start a class
The class keyword starts the plan. pass means the body is empty for now.
class Dog:
passMake one object
Dog() builds one dog object. We give it a name after it is made.
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
print(buddy.name)Add more attributes
Dot notation sets an attribute on an object. Dot notation also reads an attribute back.
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
buddy.age = 3
print(buddy.name)
print(buddy.age)Make a second object
Each object keeps its own values. Buddy does not share a name with Coco.
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
buddy.age = 3
coco = Dog()
coco.name = "Coco"
coco.age = 2
print(buddy.name)
print(coco.name)
print(buddy.age)
print(coco.age)Change an attribute
You set the attribute again in the same way. The new value replaces the old one.
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
buddy.age = 3
buddy.age = 4
print(buddy.age)Example
class Dog:
pass
buddy = Dog()
buddy.name = "Buddy"
buddy.age = 3
coco = Dog()
coco.name = "Coco"
coco.age = 2
print(buddy.name)
print(buddy.age)
print(coco.name)
print(coco.age)Key points
- Class: a blueprint that describes a kind of thing
- Object: one thing built from a class
- Instance: another word for an object of a class
- Attribute: a value stored on an object, like a name
- Use the class keyword to start a class definition
- Use Dog() to make one object from the Dog class
- Python allows other names.
- Capitals are the habit for class names.
In this example, the Dog class is an empty plan at first. Dog() makes the first object, saved as buddy. Dot notation gives buddy a name and an age. Dog() then makes a second object, saved as coco. Coco gets a different name and age. The print lines read the values back from each object.
Note
A class name starts with a capital letter by convention.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does Dog() do?