Classes and objects
Classes and instances
Create distinct objects from one class.
Lesson 49 of 63
Reading: about 1 min
Lesson + practice: about 14 min
Difficulty: Intermediate
On this page5 sections
A class defines how instances are constructed. __init__ stores each instance’s own attributes on self.
Worked example
class Session:
def __init__(self, subject, minutes):
self.subject = subject
self.minutes = minutes
first = Session("Python", 25)
second = Session("SQL", 40)
print(first.subject, first.minutes)
print(second.subject, second.minutes)Python 25 SQL 40
Why this works
Calling Session creates a new object each time. first and second have separate attribute values.
Another case
class Box:
def __init__(self, value):
self.value = value
a = Box(1)
b = Box(2)
b.value = 3
print(a.value, b.value)1 3
Practice
Create a third session and change only its minutes. What happens to first.minutes?
Check the practice result
Reveal answer
It stays 25 because each instance has its own minutes attribute.
Try another case
After a = Box(1), b = a, and b.value = 5, what is a.value?
Check your answer
Reveal answer
5. b = a does not copy the object; both names refer to the same Box instance.
Your progress
Reveal the check answer or reach the end to complete this lesson.