nathan_H

python - class method type. 본문

Programming Laguage/Python

python - class method type.

nathan_H 2019. 4. 30. 18:38

 

 

어떤 속성과 함수는 클래스 자신의 일보고, 

어떤 것은 클래스로부터 생성된 객체의 일부다.

 

 

일반적으로 class 정의에서

method 첫번째 인자가 self라면

이 method는 instance method이다.

 

이것은 일반적으로 클래스를 생성할때의

메서드 타입이다.

 

 

이와 반대로

classmethod은 클래스 전체의 영향을 미친다.

 

클래스에 대한 어떤 변화가 모든 객체에 영향을 미친다는 것이다.

사용법은 아래 코드와 같다.

class A():
    count = 0
    def __init__(self):
        A.count += 1

    def exclaim(self):
        print("i'm an A!")

    @classmethod
    def kids(cls):
        print("a has", cls.count, "little objects.")



if __name__ == "__main__":
    easy_a = A()
    breeze_a = A()
    A.kids()
    
    
    # 출력.
    a has 2 little objects.

 

method위에 @classmethod 데커레이션을 넣으면 된다.

그래고 이 methoddml 첫 번째 매개변수는

클래스 자신이다.

 

'Programming Laguage > Python' 카테고리의 다른 글

python - namedtuple  (0) 2019.04.30
python class - duck typing  (0) 2019.04.30
python - function 과 method  (0) 2019.04.30
python - namespace  (0) 2019.04.26
Decorator  (0) 2019.04.26
Comments