In Python, classes are a fundamental building block for creating objects with specific properties and behaviors. Alongside instance variables and instance methods, class variables and class methods provide additional functionality for managing data and behaviors that are shared among all instances of a class.
클래스 변수 (Class Variables)
A class variable is a variable that is shared by all instances (objects) of a class. It is defined within the class but outside any instance methods. Class variables are accessed using the class name, followed by the dot notation.
class Car:
num_of_wheels = 4 # class variable
def __init__(self, model, color):
self.model = model
self.color = color
car1 = Car("Honda", "Blue")
car2 = Car("Toyota", "Red")
print(car1.num_of_wheels) # Output: 4
print(car2.num_of_wheels) # Output: 4
print(Car.num_of_wheels) # Output: 4
In the above example, the num_of_wheels
variable is a class variable, and it is shared among all instances of the Car
class. Both car1
and car2
can access and modify this variable.
클래스 메서드 (Class Methods)
A class method is a method that belongs to the class rather than to any particular instance of the class. It is defined using the @classmethod
decorator and can be called both on the class itself and on the instances of the class.
class Car:
num_of_wheels = 4 # class variable
@classmethod
def get_num_of_wheels(cls):
return cls.num_of_wheels
car1 = Car()
car2 = Car()
print(Car.get_num_of_wheels()) # Output: 4
print(car1.get_num_of_wheels()) # Output: 4
print(car2.get_num_of_wheels()) # Output: 4
In the above example, the get_num_of_wheels
method is a class method that returns the value of the num_of_wheels
class variable. The method is defined using the @classmethod
decorator and takes the cls
argument, which refers to the class itself. The class method can be called using the class name (Car.get_num_of_wheels()
) or on any instance of the class (car1.get_num_of_wheels()
).
Conclusion
Class variables and class methods are powerful tools in Python for managing data and functionality that are shared among all instances of a class. Understanding how to use them effectively can help in creating more efficient and organized code.