Kim Jinung
Python "Class method" vs "Static method" vs "Instance method" 본문
Python "Class method" vs "Static method" vs "Instance method"
Kim Jinung 2022. 11. 16. 15:51Goal
Python의 Instance method, static method 그리고 class method의 차이점을 정리한다.
Instance method
파이썬에서 클래스를 선언하고 메서드를 생성하는 일반적인 방법은 아래와 같다.
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
def greeting(self):
print(f"Hi {self.name}")
class에서 self는 instance를 가르킨다. 즉 인스턴스로 생성 될 객체를 가르킨다.
그러므로 메서드를 선언하고 self 키워드를 이용해서 instacne attribute(속성)에 접근할 수 있다.
그러한 예가 greeting method에서 self.name을 사용하는 예이다.
위에서 self.name은 인스턴스 생성 시 부여 받은 name을 가르키게 된다.
self 키워드를 사용하지 않는 경우, 해당 attribute는 클래스로 생성한 여러 인스턴스가 공통으로 사용하는 class attribute가 된다.
아래 코드로 확인할 수 있다.
print(Person.count)
jinyes = Person('jinyes', 27)
print(Person.count)
print(jinyes.count)
jinung = Person('jinung', 27)
print(Person.count)
print(jinung.count)
다음으로 클래스의 메서드를 사용하려면 우선 아래와 같이 인스턴스로 생성해야 한다.
jinyes = Person('jinyes', '27')
jinyes.greeting()
그리고 생성한 instance의 메서드를 사용한다. 이것이 instance method다. (instance의 method다)
Static method
그런데, 클래스의 메서드를 굳이 인스턴스로 생성하지 않고 바로 호출하는 방법이 있다.
이것이 static method(정적 메서드)에 해당한다. 정적이라는 의미는, 클래스를 이용하여 인스턴스 객체를 생성하기 전에
이미 생성이 된다는 것이다.
호출 할 메서드가 instance attribute가 필요하지 않으므로 객체를 생성하지 않고 호출이 가능하다.
주로 유틸리티 성격의 메서드가 이에 해당한다.
static method는 굳이 @staticmethod 데코레이터를 붙여주지 않아도 된다. 하지만 IDE에서는 instance method와 구분하기 위해서 "...maybe static" 문구로 노란색 밑줄을 쳐준다.
이제 구체적인 static method 예시를 살펴볼 것이다.
Person class에 문자열을 모두 대문자로 치환 해주는 메서드가 필요하다고 가정하자.
해당 메서드는 instance attribute가 단 하나도 필요 하지 않다.
parametor로 받은 argument를 대문자로 치환 하고 반환만 해주면 되기 때문이다.
아래 코드에서 Person class에 uppser method를 static method로 선언했다.
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
def greeting(self):
print(f"Hi {self.name}")
@staticmethod
def upper(letters: str):
return letters.upper()
Person 클래스의 인스턴스를 생성하지 않고 곧바로 upper 메서드를 사용해서 대문자로 변환 할 수 있다.
upper_name = Person.upper('jinyes')
Class method
class method는 static method처럼 인스턴스 객체를 생성하지 않고 메서드를 바로 사용할 수 있다.
다른 점은 class attribute를 사용할 수 있다. (instance attribute는 사용할 수 없다. class method는 객체를 생성하지 않고 호출하므로 객체 생성 과정에서 만들어지는 instance attribute는 사용할 수 없는 것이다.)
우선 class 자체를 'cls'라는 관용 키워드로, 첫번째 파라미터에 부여 받는다. 여기서 cls는 Person class가 된다.
따라서 from_dict 메서드처럼 dictionary를 parametor로 받아서 Person 클래스의 인스턴스를 생성하는 방법 등으로 활용 할 수 있다.
class Person:
count = 0
def __init__(self, name, age):
self.name = name
self.age = age
Person.count += 1
def greeting(self):
print(f"Hi {self.name}")
@staticmethod
def upper(letters: str):
return letters.upper()
@classmethod
def from_dict(cls, dic: dict):
return cls(dic.get('name'), dic.get('age'))
그러한 예시
jinyes_info = {'name': 'jinyes', 'age': 27}
jinyes = Person.from_dict(jinyes_info)
다음으로 앞에서 class method는 class attribute를 사용할 수 있다고 설명했다.
반면에 static method는 class 내부에 자기자신을 제외하고 다른 attribute에 접근할 수 없다.
class method인 upper_greeting method는 instance keyword인 self를 사용하지 않는 class atrribute에 접근이 가능하다. ex) count variable, upper method
class Person:
count = 0
def __init__(self, name: str, age: int):
self.name = name
self.age = age
Person.count += 1
def greeting(self):
print(f"Hi {self.name}")
@staticmethod
def upper(letters: str):
return letters.upper()
@classmethod
def from_dict(cls, dic: dict):
return cls(dic.get('name'), dic.get('age'))
@classmethod
def upper_greeting(cls, name: str):
print(f"Hi {cls.upper(name)}")
upper_greeting 메서드는 class method이며, 내부에서 클래스를 가르키는 cls keyword를 이용해서
static method인 upper 메서드를 사용했다.
static method를 사용하는 class method를 별도의 인스턴스 객체 생성 없이 호출하는 것을 확인할 수 있다.
Person.upper_greeting('jinyes')
더 나아가 class attribute를 활용하는 메서드를 작성할 수도 있다.
class Person:
count = 0
def __init__(self, name: str, age: int):
self.name = name
self.age = age
Person.count += 1
def greeting(self):
print(f"Hi {self.name}")
@staticmethod
def upper(letters: str):
return letters.upper()
@classmethod
def from_dict(cls, dic: dict):
return cls(dic.get('name'), dic.get('age'))
@classmethod
def upper_greeting(cls, name: str):
print(f"Hi {cls.upper(name)}")
@classmethod
def count_of_instance(cls):
print(cls.count)
Person class를 사용하여 instance object를 생성할 때마다 class attribute인 count의 값이 1씩 증가한다.
count_of_instance 메서드는 Person class를 사용하여 생성한 instance의 수를 확인하는 class method다. (class의 method다)
print(Person.count)
jinyes = Person('jinyes', 27)
print(Person.count)
print(jinyes.count)
jinung = Person('jinung', 27)
print(Person.count)
print(jinung.count)
Person.count_of_instance()
요약
instance method: instance object 생성 후, instance attribute를 사용해서 작동하는 메서드
static method: instance object에 종속되는 속성을 사용하지 않기 때문에, instance object를 생성 하지 않고 바로 호출 가능한 메서드
class method: static method 처럼 바로 호출할 수 있으면서도, class attribute에 접근 및 수정이 가능한 메서드
'Language > Python' 카테고리의 다른 글
Python - Counter (0) | 2022.12.06 |
---|---|
Python - for/else (0) | 2022.12.02 |
Python - Regular Expression (0) | 2022.11.30 |
Python - GIL(Global Interpreter Lock) (0) | 2022.11.23 |
Python - container, iterable, iterator, generator (0) | 2022.11.22 |