3. Instance attributes
An instance attribute is data stored on one specific object. You create it inside a method, usually __init__, with self.attribute = value:
selfis the instance.self.nameis an attribute of that instance;nameon the right is the parameter.- Every instance created by
Dog(...)gets its ownname.
From outside the class you read an attribute with a dot: object.attribute.
You can update an existing attribute or add a new one after the object exists:
Attributes belong to the instance, not to the class: changing dog.name does not affect another dog.
Coming from JavaScript? self.name = name is this.name = name, and dog.name works the same. There are no private fields here: every attribute is readable and writable from outside.
Store one attribute
Inside __init__, store the name parameter as an attribute named name on the instance. Define Dog with __init__(self, name), create dog = Dog("Rex"), and print the attribute dog.name.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Store two attributes
Define Point with __init__(self, x, y) and store both values as attributes with the same names. Create point = Point(1, 2), then print point.x and point.y, one per line.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Two instances, two values
Define Dog with __init__(self, name) that stores self.name. Create first = Dog("Rex") and second = Dog("Luna"). Print first.name, then second.name.
Each instance keeps its own name; creating the second dog does not overwrite the first one.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Update an attribute
Define Dog with __init__(self, name) that stores self.name. Create dog = Dog("Rex"), then change its name attribute to "Max" after creation. Print the attribute.
The __init__ still receives a name for new dogs; only this instance was updated.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Add a new attribute
Define Dog with __init__(self, name) that stores self.name. Create dog = Dog("Rex"), then add an attribute named age with the value 3 after creation. Print dog.age.
Print exactly:
Create a free account to save your progress and unlock chapter 2.