본문 바로가기
파이썬

파이썬 @staticmethod @classmethod 그리고 일반메소드

by 혜룐 2015. 11. 10.
@staticmethod ?
@classmethod ?
@를 데코레이터라고 말하고,
위 둘의 차이점은
* classmethod는 첫번째 인자로 클래스 객체가 자동으로 전달된다.
* staticmethod는 클래스 내에 정의된 함수에 대해 클래스에서 바로 호출할수 있는 클래스 메소드로 만들어준다.
상속받는 경우, 이 둘의 차이를 알수 있다. ( classmethod를 활용해서 팩터리메소드패턴을 구현한단다. http://thdev.net/320 )
#-*- coding: utf-8 -*-
from unittest import TestCase
__author__ = 'catherine'
class testBla(TestCase):
@classmethod
def setUpClass(cls):
print "setupClass"
cls.sc = AA()
@classmethod
def tearDownClass(cls):
print "tearDownClass"
def testRun_staticFn(self):
self.sc.staticmethod_fn()
def testRun_classFn(self):
self.sc.classmethod_fn()
class A():
S_VAL = "foo"
def overFn_a(self):
print "overFn_a"
@staticmethod
def staticmethod_fn():
print '%s.c: S_VAL=%s' % (A.__name__, A.S_VAL)
@classmethod
def classmethod_fn(cls):
print 'cls %s.c: S_VAL=%s' % (cls.__name__, cls.S_VAL)
#print 'self %s.c: S_VAL=%s' % (self.__name__, self.S_VAL)
class AA(A):
S_VAL = "bar"
def overFn_a(self):
print "overFn_aaaaaaaaaaaaaaaa"
유닛테스트결과다.
Testing started at 오후 5:57 ...
setupClass
cls AA.c: S_VAL=bar
A.c: S_VAL=foo
tearDownClass
상속에 의해 cls가 class AA에서 선언한 bar가 되어 처리된다.
추가로..
staticmethod 나 classmethod는 객체를 인스턴스 하지 않고, 함수를 호출했다.
위 소스코드 예제에서 봤을때 A클래스의 overFn_a를 함수를 staic이나 class method처럼 호출해보면, 에러가 발생한다.
#-*- coding: utf-8 -*-
from unittest import TestCase
__author__ = 'catherine'
class testFoo(TestCase):
def testRun_overFn_instance(self):
sampleA = A()
sampleA.overFn_a()
# TypeError: unbound method overFn_a() must be called with A instance as first argument (got nothing instead)
#def testRun_overFn(self):
# A.overFn_a()
def testRun_staticFn(self):
A.staticmethod_fn()
def testRun_classFn(self):
A.classmethod_fn()
class A():
S_VAL = "foo"
def overFn_a(self):
print "overFn_a"
@staticmethod
def staticmethod_fn():
print '%s.c: S_VAL=%s' % (A.__name__, A.S_VAL)
@classmethod
def classmethod_fn(cls):
print 'cls %s.c: S_VAL=%s' % (cls.__name__, cls.S_VAL)
#print 'self %s.c: S_VAL=%s' % (self.__name__, self.S_VAL)
class AA(A):
S_VAL = "bar"
def overFn_a(self):
print "overFn_aaaaaaaaaaaaaaaa"
유닛테스트 결과를 볼까?
Testing started at 오후 6:13 ...
cls A.c: S_VAL=foo
overFn_a
A.c: S_VAL=foo
참고주소
http://soooprmx.com/wp/archives/4016