Lesson 04
Objects — Instances, Memory, and Many Values from One Class
Create a Python object from a class, compare the class with its instances, and store different instance data in each object.
An object is an instance of a class. Creating it allocates memory for that instance so you can store data and call methods.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- The definition of an object
- The two creation forms
- How a class and an object differ
- Why a missing class raises
NameError
The picture
The purpose of an object is to store data. Processing that data starts by creating the object. If the class has not been defined, creation raises NameError.
first = Badge()
second = Badge("Avery Lane")The first form fits a class whose constructor needs nothing beyond self. The second form passes values into that constructor.
| Class | Object | |
|---|---|---|
| What it is | Data members and methods | An instance of that class |
| Memory for fields | Not allocated by the class statement |
Allocated when you create the instance |
| How many | The definition exists once | Many objects can come from that one definition |
| Order | Loaded first | Created after the class exists |
The same method can run on each object, and each object keeps its own fields.
Example
class Badge:
def __init__(self, m):
self.label = m
def introduce(self):
return "Hello, " + self.label
first = Badge("Avery Lane")
second = Badge("Jordan Hale")
print(first.introduce())
print(second.introduce())
print(first is second)Both objects share the Badge methods. They do not share the label. first is second is false because they are two instances. The playground prints both greetings.
Key takeaways
-
An object is an instance: memory for the class members
-
Create it with
ClassName()orClassName(values) -
One class can produce many objects
-
A missing class name raises
NameError -
Next: Constructors — fill the object at the moment it is created
-
Previous: Inside a Class
Loading playground…
Check your understanding
Objects quiz
An object is:
1 / 10