sec04 - Python Class Variables, Class Methods, and Static Methods Explained Clearly
スポンサーリンク

What Is a Class Variable? — How Shared Variables Work

A class variable refers to a “value shared across the entire class.” For example, when managing data such as “the total number of cars sold for all instances of the Car class,” you use a class variable because the data is common to all instances.

class Car:
    # Class variable (shared across all instances)
    total_cars = 0

    def __init__(self, name):
        # Instance variable (unique to each instance)
        self.name = name
        # Increment the class variable
        Car.total_cars += 1

    def show_info(self):
        print(f'{self.name} has been sold.')
        print(f'Current total sold: {Car.total_cars}')

car1 = Car('Prius')
car1.show_info()
car2 = Car('Aqua')
car2.show_info()
Prius has been sold.
Current total sold: 1
Aqua has been sold.
Current total sold: 2

The key points of this sample code are as follows:

  • total_cars = 0 is a class variable and represents the single shared value across the entire class.
    • If a variable is defined inside the class block but outside any method, it is recognized as a class variable. Typically, it is written immediately after the class line.
  • def __init__(self, name): is a special method called automatically when an instance is created.
  • Car.total_cars += 1 increases the total number of cars each time a new instance is created. To access a class variable, use the format ClassName.class_variable.

How Class Methods (classmethod) Work

A class method is often used when working with class variables. It allows you to perform actions that relate to the class itself, rather than to individual instances.

You define a class method using the @classmethod decorator and use cls as the first parameter.

class Car:
    total_cars = 0

    def __init__(self, name):
        self.name = name
        Car.total_cars += 1

    @classmethod
    def show_total(cls):
        print(f'Current total sold: {cls.total_cars}')


car1 = Car('Prius')
car2 = Car('Aqua')
Car.show_total()  # Calling the class method
Current total sold: 2

The key points of this sample code are as follows:

  • @classmethod
    • This decorator tells Python that the method is a “class method.”
  • def show_total(cls):
    • The first parameter of a class method is cls, which refers to the class itself.
    • It’s similar to self, which refers to an instance, but cls represents the entire class.
  • print(f"Current total sold: {cls.total_cars}")
    • Here, the class variable is accessed through cls rather than the class name.
    • This makes the method reusable for subclasses as well.
  • Car.show_total()
    • You can call the method directly using ClassName.class_method() without creating an instance.
スポンサーリンク

Static Methods (staticmethod) — Features and Usage

A static method is used to define a general-purpose function that doesn’t access class or instance data. It’s ideal for helper operations such as string formatting or simple calculations.

You define it using the @staticmethod decorator.

class Car:
    total_cars = 0

    def __init__(self, name):
        self.name = name
        Car.total_cars += 1

    @staticmethod
    def show_message(greeting):
        print(f'{greeting}. Welcome to the Car class!')


Car.show_message('Hello')  # Hello. Welcome to the Car class!
Hello. Welcome to the Car class!
  • @staticmethod
    • This decorator explicitly states that the function does not depend on either the class or its instances.
  • def show_message(greeting):
    • A static method doesn’t take self or cls as parameters. When parameters are needed, define them just like regular functions.
  • Static methods are often used to group helper functions related to a class.
    • For example, methods for formatting car names or prices would fit this use case.
  • Car.show_message()
    • Static methods can be called directly from the class without creating an instance.

Factory Methods (Practical Use of classmethod)

A factory method is used when you want to create an instance after performing preprocessing on input data, instead of using the regular constructor (__init__).

This technique allows for flexible instance creation with pre-validated or preformatted data. It’s a widely used design pattern that hides complex initialization logic and makes instance creation easier for users.

class Car:
    total_cars = 0

    def __init__(self, name):
        self.name = name
        Car.total_cars += 1

    @classmethod
    def from_string(cls, name_str):
        # Factory method that formats the string before creating the Car instance
        name = name_str.strip().capitalize()
        return cls(name)

    @classmethod
    def show_total(cls):
        print(f'Current total sold: {cls.total_cars}')


car = Car.from_string(' corolla ')
print(car.name)
Car.show_total()
Corolla
Current total sold: 1
  • @classmethod
    • A factory method is also defined as a class method.
    • Here, a new instance is created using cls(name).
      • cls(name) is equivalent to Car(name).
  • def from_string(cls, name_str):
    • Instead of using __init__ directly, the string is cleaned and formatted before creating an instance.
    • This is useful when you want to “preprocess input and return a clean, properly formatted instance.”
  • “Factory method” means:
    • A method that hides complex initialization and provides a simplified way to create instances.
    • In other words, it acts like a single, unified “production line” for creating cars.

Summary of Python Class Design

Difference Between Class Variables and Instance Variables

ItemClass VariableInstance Variable
Definition LocationDirectly under the class definitionDefined inside __init__() using self.variable_name
OwnerShared by the entire classUnique to each instance
Access MethodClassName.variable or self.variableself.variable
Effect of ChangesAffects all instancesAffects only that instance
Main UseShared information (e.g., number of created instances, common settings)Instance-specific information (e.g., car color, speed)

For example, information like “the total number of cars created” is suitable for a class variable, while “color” or “fuel level” fits as instance variables.

How to Choose Between Functions, Instance Methods, Class Methods, and Static Methods

TypeDefinition LocationCall MethodFirst ArgumentRelation to Class/InstanceMain Purpose
Regular FunctionOutside the classfunction_name()NoneUnrelated to classEncapsulate general-purpose operations
Instance MethodInside the classinstance.method()selfBelongs to an instance (can access instance variables)Behavior of individual objects (e.g., driving a car)
Class MethodInside the class (@classmethod)ClassName.method() or instance.method()clsBelongs to the class itself (can access class variables)Operations shared by all instances (e.g., manage total count)
Static MethodInside the class (@staticmethod)ClassName.method() or instance.method()NoneIndependent of both class and instanceUtility processing (e.g., input validation)
  • self – Refers to “this instance itself.” Used to access instance variables.
  • cls – Refers to “this class itself.” Used to work with class variables.
  • @staticmethod – Defines an “independent function inside a class.” It doesn’t receive self or cls.
GoalBest Method Type
Modify individual object stateInstance Method
Operate on class-level shared dataClass Method
Use as a general utility functionStatic Method
スポンサーリンク