# Python Method **Published by:** [Primrose](https://paragraph.com/@primrose/) **Published on:** 2022-09-30 **URL:** https://paragraph.com/@primrose/python-method ## Content Instance Method클래스에 아무 decorator 없이 method를 선언하면 해당 method는 instance method로 취급이 되며, 첫 번째 parameter로 클래스의 instance가 넘어오게 된다. 이 첫 번째 parameter의 이름은 self라고 하며, self.attribute …를 통해 instance/class 속성에 접근하거나 instance/class method를 호출할 수 있다.class Counter: def __init__(self, value=0): self.value = value def increment(self, delta=1): self.value += delta def decrement(self, delta=1): self.value -= delta 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를 작성할 때 유용하게 사용된다.class Counter: def __init__(self, value=0): self.value = value def increment(self, delta=1): self.value += delta def decrement(self, delta=1): self.value -= delta @classmethod def newCounterFromTuple(cls, tup): return cls(tup[0]) @classmethod def newCounterFromArray(cls, arr): return cls(arr.pop()) Static Method@staticmethod decorator를 사용해서 method를 선언하면 해당 method는 정적 method가 된다. 정적 method는 instance method나 class method와 달리 첫 번째 parameter가 할당되지 않는다. 따라서 정적 method 내에서는 instance/class 속성에 접근하거나, instance/class method를 호출하는 것이 불가능하다. 바꾸어말하면, 접근할 필요가 없을 때 사용하면 되기 때문에, 주로 utility method를 작성할 때 유용하다.class Counter: def __init__(self, value=0): self.value = value def increment(self, delta=1): self.value += delta def decrement(self, delta=1): self.value -= delta @classmethod def newCounterFromTuple(cls, tup): return cls(tup[0]) @classmethod def newCounterFromArray(cls, arr): return cls(arr.pop()) @staticmethod def PrintInformation(): print("This is a counter") ## Publication Information - [Primrose](https://paragraph.com/@primrose/): Publication homepage - [All Posts](https://paragraph.com/@primrose/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@primrose): Subscribe to updates