Static Methods and Variables - Rybd04/2143-OOP GitHub Wiki

Definition

Static Methods and Variables

Static methods and static variables belong to the class itself rather than any instance of the class.

Explanation

This variable is shared among all instances of a class. It is like how all cars have four wheels.

Basic Code Example

class Counter:
    count = 0  # static variable

    def __init__(self):
        Counter.count += 1

print(Counter.count)  # Output: 0
a = Counter()
b = Counter()
print(Counter.count)  # Output: 

Image

image

Additional Resources

https://www.geeksforgeeks.org/static-method-in-java-with-examples/ https://codehs.com/textbook/apcsa_textbook/5.7