기본 콘텐츠로 건너뛰기

[python] classmethod와 abstractmethod

classmethod와 abstractmethod를 비슷한 방법으로 사용을 할 수 있다.
우선 classmethod와 비교가 되는것이 staticmethod이다.
간단하게 classmethod와 staticmethod가 어떤건지 부터 비교를 해보자.


@staticmethod

p.py
1
2
3
4
5
6
7
8
9
10
11
12
class MethodTest(object):
    __c_test = 1
    def __init__(self):
        pass
 
    @staticmethod
    def s_print():
        print('is staticmethod')
 
MethodTest.s_print()
MethodTest.s_print()
MethodTest.s_print()
cs

$python p.py

>>> is staticmethod
is staticmethod
is staticmethod

staticmethod는 해당 클래스를 namespace처럼 사용하기 위해 사용을 한다. 즉 해당 객체를 생성하지 않아도 해당 클래스 이름만 가지고 해당 method를 호출을 할 수있다.
staticmethod는 self인자를 받지 않는다.


@classmethod

p.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MethodTest(object):
    __c_test = 1
    def __init__(self):
        pass
 
    @classmethod
    def c_print(cls):
        cls.__c_test += 1
        print(cls.__c_test)
 
methodTest1 = MethodTest()
methodTest2 = MethodTest()
methodTest3 = MethodTest()
methodTest1.c_print()
methodTest2.c_print()
methodTest3.c_print()
cs

$python p.py

>>> 2
3
4

classmethod는 해당 클래스로 생성된 객체마다 생성이 되지 않고 생성된 모든 객체가 동일한 메소드로 접근을 하게된다. classmethod는 첫번쨰 인자로 해당 클래스 인자를 받게된다. 


classmethod를 이용해서 인터페이스를 상속받아 하위 클래스에서 해당 클래스를 재정의 하는 것을 구현을 해보자.

우선 인터페이스랑 하위 클래스에서 어떤 메소드를 사용할지 상위 클래스에서 미리 정의를 해두는 것을 말한다. 사용설명서라고 생각을 하면 쉽게 일해를 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Parents(object):
    def __init__(self):
        print('Parents Initional')
 
    @classmethod
    def c_print(cls):
        pass
 
class Children(Parents):
    def __init__(self):
        super(__class__, self).__init__()
        print('Children Initional')
 
    def c_print(self):
        print('interface tesst')
 
c1 = Children()
c1.c_print()
cs

childrend은 Parents라는 클래스를 상속을 받아왔다. 이떄 parents는 c_print()를 classmethod로 선언을 하였다.

$python p.py

>>> Parents Initional
Children Initional interface tesst
이렇게 정상적으로 출력이 된다.

여기서 문제가 있다.
인터페이스로 만든 메소드를 하위 클래스에서 반드시 정의를 해서 사용해야 한다면 

1
2
3
@classmethod
def c_print(cls):
    raise NotImplementedError()  
cs

위와 같이 수정을 하면 하위 클래스에서 해당 메소드를 재 정의를 하지 않으면 에러가 발생을 한다.

$python p.py

>>> Traceback (most recent call last):
File "p.py", line 169, in c1.c_print() File "p.py", line 158, in c_print raise NotImplementedError() NotImplementedError
에러를 발생한다. 
하위 클래스에서 재정의를 한다면 정상적으로 실행이 이루어 진다.

근데 먼가 raise를 넣어서 강제로 에러를 발생하는건 먼가 깔끔한것 같지 않다.

abstractmethod를 이용하여 raise를 이용하지 않고 자체적으로 에러를 발생시킬 수 있다.


@abstractmethod

p.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#추상클래스를 사용하기 위해 선언
from abc import ABCMeta, abstractmethod
 
class Interface(metaclass=ABCMeta):
    @abstractmethod
    def interface_test(self, *args, **kwargs):
        pass
 
class Mung(Interface):
    def __init__(self):
        print('initional')
 
    def interface_test(self):
        print('interface test')
 
 
if __name__ == "__main__":
    munggae = Mung()
    munggae.interface_test()
cs

$python p.py

>>> initional interface test
정상적으로 출력이 이루어 졌다.
interface클래스를 추상 클래스로 사용하기 위해 ABCmeta를 상속을 받았다.

만약에 Mung클래스에서 interface_test를 재정의를 하지 않고 Mung객체를 생성을 한다면?

Traceback (most recent call last):
File "p.py", line 140, in
munggae = Mung()
TypeError: Can't instantiate abstract class Mung with abstract methods interface_test
위와 같은 에러가 발생을 할 것이다.


abstractmethod를 쓰면 classmethod와 다르게 해당 객체가 생성이 되는 동시에 해당 method가 재정의가 이루어 지는지 확인을 한다.





댓글

이 블로그의 인기 게시물

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...

[css] css로 프린트 방지하기

웹에서 프린트 제어가 불가능 한 줄 알았는데 프린트 클릭 시  스크립트로 해당 이벤트를 받아올 수 있다. 하지만 스크립트를 사용하는 방법은 브라우저마다 작동을 하지 않을 수 있다. 좀 더 찾아보니 css로 인쇄되는 영역을 제어를 해줄 수 있다.  @media print 를 이용하면 된다. < html > < head > < title > print test page < / title > < style > @media print { . np { display : none ; } } < / style > < / head > < body > < div class = "np" > test < / div > < div > test1 < / div > < div > test1 < / div > < div > test1 < / div > < / body > < / html > 위 코드를 보면 np 클래스를 @media print에 넣어주었다. @media print는 인쇄됐을 때의 스타일을 지정을 해주는 것이다.  위에서는 해당 페이지를 인쇄할 때 p를 display : none으로 가려주었다. @media print를 이용하면 좀 더 멋진 인쇄물을 만들 수 ...

[알고리즘] snake게임 알고리즘

막무가네로 알고리즘을 공부하면 재미가 없으니 게임을 접목하여 다루어 보도록 하겠습니다. 게임의 대상은 스네이크 게임입니다. 많은 사람들은 어릴 때 뱀게임을 많이 해봤을 것 입니다. 이번에 다뤄볼 주제는 뱀이 움직임을 어떻게 구현을 할지 알아보겠습니다. 뱀은 크게 3가지의 경우가 있습니다 1. 가장 중요한 뱀을 움직이기 2. 음식먹기 이때 뱀은 크기가 늘어나야 합니다. 3. 뱀이 움직이는 정책   - 뱀이 움직이지 못하는 경우는 : 우측방향에서 좌측 방향으로 OR 위에 아래 방향고 같이 180도 반전되는 움직임은 막겠습니다. 순수한 알고리즘을 만드는 과정이기 때문에 음식을 먹었는지 안먹었는지 판단하는 부분은 랜덤으로 판단을 하도록 하겠습니다. def is_eat(): return random.choice([1, 0]) 랜덤으로 1, 0을 반환을 해줍니다. 실제로 게임을 만든다면 해당 함수는 뱀의 머리가 음식의 좌표와 같은지 검사를 해주면 되겠습니다. key_position_map = { 'w': [-1, 0], # up 's': [1, 0], # down 'a': [0, -1], # left 'd': [0, 1] # right } direction = key_position_map.get('d') 다음으로는 키맵핑을 한 오브젝트 입니다. direction은 현재 뱀의 방향을 나타냅니다. snake_body = [[2, 3], [1, 3],[1, 2], [1, 1]] 주인공이 되는 뱀의 좌표들 입니다. while True: key = input() new_direction = key_position_map.get(key) if new_direction and direction_check(direction, new_direction): directi...