Attributes
Attributes
Objects can store data.
That data is called attributes.
Attributes describe an object.
What Is an Attribute?
An attribute is a variable inside an object.
Examples for a car:
- brand
- color
- speed
Examples for a student:
- name
- age
- score
Why Attributes Matter
Attributes let each object have its own data.
Two objects from the same class can store different values.
Create Attributes
Use a dot .
object_name.attribute = value
Example: Car Attributes
class Car:
pass
car1 = Car()
car1.brand = "Toyota"
car1.color = "Blue"
print(car1.brand)
print(car1.color)
Output
Toyota
Blue
Another Object
car2 = Car()
car2.brand = "Ford"
car2.color = "Red"
print(car2.brand)
print(car2.color)
Output
Ford
Red
Same Class, Different Data
Both objects come from Car, but each stores different values.
Student Example
class Student:
pass
tom = Student()
tom.name = "Tom"
tom.score = 85
print(tom.name)
print(tom.score)
Output
Tom
85
Change Attributes
You can update them.
tom.score = 90
print(tom.score)
Output
90
Common Beginner Error
Using an attribute before creating it.
print(car1.speed)
This causes an error if speed was never added.
Code Along
Create a class called Book.
Create one object.
Add:
- title
- price
Print both values.
Mini Challenge
Create a class called Phone.
Steps:
-
Create one object named
phone1 -
Add attributes:
- brand = Apple
- model = iPhone
- price = 999
-
Print all values
Expected output:
Apple
iPhone
999
Real World Use Case
Apps use attributes for user names, product prices, game health, account balances, and settings.
Quiz
- What is an attribute?
- How do you create an attribute?
- Can two objects have different attribute values?
- Can attributes be updated?
Assignment
Create a class called Movie. Add title and year to two movie objects.
Summary
You learned that attributes store data inside objects and give each object its own information.