Editor settings

General settings

Save settings

Learn to program with Python

Assigning object's properties #

We can both access and assign an object's property by using the . (dot notation). The property is attached to each object and not shared among other objects created by the same class.

For example:

class Car:
    pass

new_car = Car()
new_car.brand = "Toyota"
print(new_car.brand) # Toyota

another_car = Car()
print(another_car.brand) # AttributeError: 'Car' object has no attribute 'brand'

In the example above, we create a new object new_car from the class Car. We then assigned the property brand with the value "Toyota" to the new_car object. We can then access the brand property by using new_car.brand. But when we try to access the same property in another car object another_car, we then get the error AttributeError telling us that the object does not have the attribute brand yet.


Exercise #

  • Assign a number to the property age to the object person.
  • Assign another number to the property age to the object another_person.

Tests #

  • person.age should be a number from 1 to 100
  • another_person.age should be a number from 1 to 100
  • person.age and another_person.age should not be the same number
Output will be displayed here