Class Variables - Rybd04/2143-OOP GitHub Wiki

Definition

Class Variables

a class variable is a variable that is shared across all instances of a class. It is declared within the class, but outside of any instance methods

Explanation

This is like how all dogs have four legs and a tail regardless of length/color

Basic Code Example

class Car:
    wheels = 4  # class variable

    def __init__(self, color):
        self.color = color  # instance variable

car1 = Car("Red")
car2 = Car("Blue")

print(car1.wheels)  # Output: 4
print(car2.wheels)  # Output: 4

Car.wheels = 6  # Change class variable for all instances

print(car1.wheels)  # Output: 6
print(car2.wheels)  # Output: 6

wheels is a class variable shared across all Car instances and color is an instance variable unique to each object.

Image

image

Additional Resources

https://blog.heycoach.in/class-variables-in-c/ https://forum.arduino.cc/t/c-question-class-scoped-variable-shared-between-all-instances-of-the-class/875156