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
ageto the objectperson. - Assign another number to the property
ageto the objectanother_person.
Tests #
person.ageshould be a number from1to100another_person.ageshould be a number from1to100person.ageandanother_person.ageshould not be the same number
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules