CodingNic

Object-Oriented Programming

Attributes

Object-Oriented Programming 26 min read

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 .

python
object_name.attribute = value

Example: Car Attributes

python
class Car:
    pass

car1 = Car()

car1.brand = "Toyota"
car1.color = "Blue"

print(car1.brand)
print(car1.color)

Output

text
Toyota
Blue

Another Object

python
car2 = Car()

car2.brand = "Ford"
car2.color = "Red"

print(car2.brand)
print(car2.color)

Output

text
Ford
Red

Same Class, Different Data

Both objects come from Car, but each stores different values.

Student Example

python
class Student:
    pass

tom = Student()
tom.name = "Tom"
tom.score = 85

print(tom.name)
print(tom.score)

Output

text
Tom
85

Change Attributes

You can update them.

python
tom.score = 90
print(tom.score)

Output

text
90

Common Beginner Error

Using an attribute before creating it.

python
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:

text
Apple
iPhone
999

Real World Use Case

Apps use attributes for user names, product prices, game health, account balances, and settings.

Quiz

  1. What is an attribute?
  2. How do you create an attribute?
  3. Can two objects have different attribute values?
  4. 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.