Python Method
Instance Method
클래스에 아무 decorator 없이 method를 선언하면 해당 method는 instance method로 취급이 되며, 첫 번째 parameter로 클래스의 instance가 넘어오게 된다.
이 첫 번째 parameter의 이름은 self
라고 하며, self.attribute …
를 통해 instance/class 속성에 접근하거나 instance/class method를 호출할 수 있다.
Class Method
@classmethod decorator를 사용해서 클래스에 method를 선언하면
해당 method는 class method가 되며, 첫 번째 parameter로 self
가 아닌 cls
라는 이름으로 클래스 자체가 넘어오게 된다.
클래스 method는 이 cls
를 통해 클래스 속성에 접근하거나, 다른 class method를 호출할 수 있다.
하지만, instance method와 달리 instance 속성에 접근하거나 다른 instance method를 호출하는 것은 불가능하다.
Python에서는 생성자 overloading을 지원하기 때문에, Class method는 주로 Factory method를 작성할 때 유용하게 사용된다.
Static Method
@staticmethod decorator를 사용해서 method를 선언하면 해당 method는 정적 method가 된다.
정적 method는 instance method나 class method와 달리 첫 번째 parameter가 할당되지 않는다.
따라서 정적 method 내에서는 instance/class 속성에 접근하거나, instance/class method를 호출하는 것이 불가능하다.
바꾸어말하면, 접근할 필요가 없을 때 사용하면 되기 때문에, 주로 utility method를 작성할 때 유용하다.
Last updated