
Table of Contents(目次)
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 = 0is 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
classline.
- 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
def __init__(self, name):is a special method called automatically when an instance is created.Car.total_cars += 1increases the total number of cars each time a new instance is created. To access a class variable, use the formatClassName.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, butclsrepresents the entire class.
- The first parameter of a class method is
print(f"Current total sold: {cls.total_cars}")- Here, the class variable is accessed through
clsrather than the class name. - This makes the method reusable for subclasses as well.
- Here, the class variable is accessed through
Car.show_total()- You can call the method directly using
ClassName.class_method()without creating an instance.
- You can call the method directly using
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
selforclsas parameters. When parameters are needed, define them just like regular functions.
- A static method doesn’t take
- 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 toCar(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.”
- Instead of using
- “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
| Item | Class Variable | Instance Variable |
|---|---|---|
| Definition Location | Directly under the class definition | Defined inside __init__() using self.variable_name |
| Owner | Shared by the entire class | Unique to each instance |
| Access Method | ClassName.variable or self.variable | self.variable |
| Effect of Changes | Affects all instances | Affects only that instance |
| Main Use | Shared 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
| Type | Definition Location | Call Method | First Argument | Relation to Class/Instance | Main Purpose |
|---|---|---|---|---|---|
| Regular Function | Outside the class | function_name() | None | Unrelated to class | Encapsulate general-purpose operations |
| Instance Method | Inside the class | instance.method() | self | Belongs to an instance (can access instance variables) | Behavior of individual objects (e.g., driving a car) |
| Class Method | Inside the class (@classmethod) | ClassName.method() or instance.method() | cls | Belongs to the class itself (can access class variables) | Operations shared by all instances (e.g., manage total count) |
| Static Method | Inside the class (@staticmethod) | ClassName.method() or instance.method() | None | Independent of both class and instance | Utility 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 receiveselforcls.
| Goal | Best Method Type |
|---|---|
| Modify individual object state | Instance Method |
| Operate on class-level shared data | Class Method |
| Use as a general utility function | Static Method |






