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
armswith the value2to the classPerson
Tests #
Person.armsmust be2
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