python
classmethod vs staticmethod
택시짱
2022. 1. 16. 18:18
classmethod
classmethod는 instance에 독립적이다
- classmethod는 instance에서도 실행이 되고 class 자체에서도 실행 가능
- instance마다 값이 변하지 않음
class에 종속적 이다
- classmethod는 클래스를 통해 호출 할 수있다. 그래서 클래스에 종속적 이다.
classmethod는 클래스 변수에 접근(변경)이 가능하다.
python에서
help(classmethod)
를 입력시class classmethod(object) | classmethod(function) -> method | | Convert a function to be a class method. | | A class method receives the class as implicit first argument, | just like an instance method receives the instance. | To declare a class method, use this idiom: | | class C: | @classmethod | def f(cls, arg1, arg2, ...): | ... | | It can be called either on the class (e.g. C.f()) or on an instance | (e.g. C().f()). The instance is ignored except for its class. | If a class method is called for a derived class, the derived class | object is passed as the implied first argument. | | Class methods are different than C++ or Java static methods. | If you want those, see the staticmethod builtin.
staticmethod
staticmethod는 instance에 독립적이다.
- classmethod와 같이 instance를 생성하지 않아도 된다.
클래스의 상태에 독립적이다.
- staticmethod는 암시적 인자(self, cls)를 입력 받지 않는다.
- 클래스의 상태에 접근(조작) 할 수 없다.
클래스에 종속적 이다.
- staticmethod도 클래스의 속성이다.
python에서
help(staticmethod
를 입력시class staticmethod(object) | staticmethod(function) -> method | | Convert a function to be a static method. | | A static method does not receive an implicit first argument. | To declare a static method, use this idiom: | | class C: | @staticmethod | def f(arg1, arg2, ...): | ... | | It can be called either on the class (e.g. C.f()) or on an instance | (e.g. C().f()). The instance is ignored except for its class. | | Static methods in Python are similar to those found in Java or C++. | For a more advanced concept, see the classmethod builtin.
classmethod vs staticmethod
- classmethod는 cls를 첫 번째 매개변수로 사용하지만 staticmethod는 특정 매개변수가 필요하지 않다.
- classmethod는 클래스의 상태에 접근 또는 수정 가능하지만 staticmethod는 클래스의 상태에 접근 또는 수정이 불가능 하다.
- staticmethod는 클래스의 상태에 대해서 전혀 알지 못한다. 일부 매개변수를 사용하고 해당 매개변수에 의해 작동하는 유틸리티 유형의 메소드이다. classmethod에는 클래스가 매개변수로 있어야 한다.
언제 무엇을 사용할까?
classmethod
- factory method를 생성하기 위해 classmethod를 사용
- 동물의 이름과 나이를 입력 받아 인스턴스를 생성
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
- 동물의 이름과 동물의 태어난 연도를 이용하여 인스턴스를 생성하고 싶음
import datetime
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_year(cls, name, year):
return cls(name, datetime.datetime.now().year - year)
>>> Animal.from_yaer('야옹이', 2014)
staticmethod
- utility method를 생성하기 위해 staticmethod를 사용
- 임의의 숫자를 받아 읽기 쉽게
,
를 넣어 반환 하는 메소드를 생성
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def humanify_number(n):
return f'{n:,}'
>>> Animal.humanify_number(1000)
>>> Animal.humanify_number(10*9*8*7*6*5*4*3*2*1)
'1,000'
'3,628,800'
참고한 사이트: https://shoark7.github.io/programming/python/staticmethod-and-classmethod-in-Python
반응형