Editor settings

General settings

Save settings

Learn to program with Python

Class properties #

Class properties are defined at the class level and are shared among all objects created with that class.

When you change a class property, the new value is shared among all instances of the class, including instances that were created before the attribute was changed. For example:

class Car:
    wheel = 4 # <- A class property

car1 = Car()
car2 = Car()

print(Car.wheel) # Output: 4
print(car1.wheel) # Output: 4
print(car2.wheel) # Output: 4

Car.wheel = 3 # <- Change made to Car class instead of car1 or car2.

car3 = Car()

print(Car.wheel) # Output: 3
print(car1.wheel) # Output: 3
print(car2.wheel) # Output: 3
print(car3.wheel) # Output: 3

In the example above, we could see that when we change the class property with Car.wheel, the value is changed on all objects created with the Car class, both before and after the change.


Exercise #

  • Create a class property named arms with the value 2 to the class Person

Tests #

  • Person.arms must be 2
Output will be displayed here