티스토리 뷰

참조: https://blog.naver.com/parkjy76/30167615254


Python에서는 static(정적) 메소드를 데코레이터로 정의 할 수 있는데 @staticmethod, @classmethod를 사용한다.
이 둘의 차이점은 classmethod의 경우는 첫번째 인수가 클래스를 지정하는데 반해 staticmethod는 이런 룰이 없다.
이로 인해 상속받는 경우 동작이 달라진다.


class foo(object):
    name = 'foo'
@staticmethod def get_name_static(): print foo.name
@classmethod def get_name_class(cls): print cls.name

실행 결과는 아래와 같다.

>>> foo.get_name_static()
foo
>>> foo.get_name_class()
foo

위를 보면 동작의 차이점을 알수 없다. 하지만 상속받아 사용하는 경우를 보자.

class bar(foo):
   name = 'bar'

실행 결과를 보면 아래와 같다.

>>> bar.get_name_static()
foo
>>> bar.get_name_class()
bar

get_name_static은 아래와 같이 처리되는데 반해

print foo.name

get_name_class에서는 상속에 의해 cls가 bar가 되어 처리된다.

print bar.name


이번에는 반대로 셋을 하는 경우는 어떤지 보기로 하자
먼저 @classmethod의 경우이다.

class foo(object):
    @classmethod
    def set_name(cls, name):
        cls.name = name

class bar(foo): pass
 
foo.set_name("foo")
print foo.name
print bar.name

bar.set_name("bar")
print foo.name
print bar.name 

실행 결과는 아래와 같다.

foo
foo
foo
bar

이번에는 @staticmethod의 결과를 보자.

class foo(object):
    @staticmethod
    def set_name(name):
        foo.name = name

class bar(foo): pass
 
foo.set_name("foo")
print foo.name
print bar.name

bar.set_name("bar")
print foo.name
print bar.name

실행 결과는 아래와 같다.

foo
foo
bar
bar

당연한것이 @staticmethod는 scope를 직접지정해야 되는데 반해 @classmethod는 cls를 기본 변수로 받아 이를 이용하므로 LSB의 동작처럼 상속받은 클래스가 cls가 된다는 것이다.

php에서는 static()을 사용하여 cls와 같은 방식으로 사용할수 있다. 

'BackEnd > Python' 카테고리의 다른 글

[퍼옴] Python __str__, __repr__ 의 차이점  (0) 2018.02.25
python getattr, rsplit  (0) 2018.02.21
python에서 private로 처리 하고 싶다면? @Property  (0) 2018.01.31
[퍼옴] Python *, ** 의미?  (0) 2018.01.30
Python 메모리  (0) 2017.12.15
댓글
공지사항
최근에 올라온 글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함