Start learning free

LESSON 284 OF 673 · FUNCTIONS & CLASSES

Attributes in Python

Lesson

TL ; DR:

  • An attribute is a piece of data attached to an object. In Python you don't declare them up front — you just assign them with the dot operator:

    dog = Dog()
    dog.name = "Rex"
    dog.age = 4
    

  • Each object has its own attributes, so two dogs can have different names without interfering.



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical. We need a way to attach data to each object.

In Python, the data attached to an object is called an attribute. (Other languages call them fields or properties — same idea.)


Setting attributes

Python is a dynamic language: you don't have to declare an attribute before using it. Just assign to it with the dot operator:

dog = Dog()
dog.name = "Rex"
dog.age = 4

That's it. After this, dog has a name attribute equal to "Rex" and an age attribute equal to 4.


Reading attributes

print(dog.name)   # Rex
print(dog.age)    # 4

You read attributes the same way you set them — with the dot operator.


Each object has its own attributes

rex = Dog()
luna = Dog()
rex.name = "Rex"
luna.name = "Luna"
# rex.name is "Rex", luna.name is "Luna" — they don't interfere.

Note: in the next lesson you'll learn the cleaner way

Setting attributes one at a time after creation is verbose. In the next lesson we'll see how a __init__ method (constructor) lets you initialize attributes in one step. For now, do it the manual way.


Your task

The Dog class is already defined for you. Below it, set dog.name to "Rex" and dog.age to 4. The pre-filled print will then show:

Rex is 4 years old
STEP 1 OF 1
    Ctrl + Enter to check