Static Members

Not all methods need to belong to a specific object. Static methods are called on the class itself, not on an instance. Class variables are shared across all instances — there is only one copy.

Class Variables

class Counter:
    count = 0  # class variable — one copy, shared by all

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

a = Counter()
b = Counter()
print(Counter.count)  # → 2
2

Class variables are accessed via ClassName.variable. Every instance sees the same value.

Static Methods (@staticmethod)

class Converter:
    @staticmethod
    def km_to_miles(km):
        return km * 0.621371

# No instance needed — call on the class directly
print(Converter.km_to_miles(10))  # → 6.21371
6.21371
  • @staticmethod decorator marks the method as static
  • No self parameter — it cannot access instance variables
  • Call it as ClassName.method() — no object required
  • Use static methods for utility functions that logically belong to the class

When to Use Static vs Instance Methods

  • Instance method: needs to read or write self — e.g. account.deposit(50)
  • Static method: pure utility, no instance data needed — e.g. MathHelper.square(5)

Your Task

  1. Complete square(n): return n ** 2
  2. Complete circle_area(r): return math.pi * r ** 2(use math.pi — it is already imported)
  3. Call both methods on the class: MathHelper.square(5) and MathHelper.circle_area(2)
Section 1/4Class Variables

Class Variables

Class variables are accessed via ClassName.variable. Every instance sees the same value.

Static Members

Not all methods need to belong to a specific object. Static methods are called on the class itself, not on an instance. Class variables are shared across all instances — there is only one copy.

Class Variables

class Counter:
    count = 0  # class variable — one copy, shared by all

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

a = Counter()
b = Counter()
print(Counter.count)  # → 2
2

Class variables are accessed via ClassName.variable. Every instance sees the same value.

Output:

Click "Check" to run your code.