기본 콘텐츠로 건너뛰기

[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가 재정의가 이루어 지는지 확인을 한다.





댓글

이 블로그의 인기 게시물

[git] git log 확인하기

git log를 통해서 커밋 이력과 해당 커밋에서 어떤 작업이 있었는지에 대해 조회를 할 수 있다. 우선 git에서의 주요 명령어부터 알아보겠다. $ git push [branch name] $ git pull [branch name] 여기서 branch name은 로컬일 경우 해당 브런치 이름만 적으면 되지만 깃허브 원격 저장소로 연결을 원할 경우는 해당 브런치 이름 앞에 꼭 origin을 붙이도록 한다. $ git brnch [branch name] $ git checkout [branch name] branch일경우 해당 브런치를 생성을 한다. 여기서 현재의 브런치를 기준으로 브런치를 따는것이다. checkout은 브런치를 바꾸는 것이다.(HEAD~[숫자]를 이용하면 해당 커밋으로 움직일수 있다.. 아니면 해당 커밋 번호를 통해 직접 옮기는것도 가능하다.) -> 해당 커밋으로 옮기는 것일뿐 실질적으로 바뀌는 것은 없다. 해당 커밋으로 완전히 되돌리려면 reset이라는 명령어를 써야한다. 처음 checkout을 쓰면 매우 신기하게 느껴진다. 막 폴더가 생겼다가 지워졌다가 ㅋㅋㅋㅋㅋ  master 브런치에서는 ht.html파일이 존재하지만 a브런치에서는 존재하지않는다. checkout 으로 변경을 하면 D 로 명시를 해준다.  $ git log 해당 브런치의 커밋 내역을 보여준다. a 브런치의 커밋 내역들이다. (머지 테스트를 하느라 커밋 내용이 거의 비슷하다 ㅋㅋ) master 브런치의 커밋 내역들이다. 커밋 번호, 사용자, 날짜, 내용순으로 등장을 한다. 이건 단순히 지금까지의 내역을 훑어보기 좋다. 좀더 세밀한 내용을 봐보자. $ git log --stat --stat을 붙이면 기존의 로그에서 간략하게 어떤 파일에서

[git] pull을 하여 최신코드를 내려받자

보면 먼가 로고가 다르게 뜨는것을 확인을 할 수가있다. C:\Users\mung\Desktop\etc\study\python-gene>git checkout remotes/origin/master Note: checking out 'remotes/origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example:   git checkout -b HEAD is now at 29e282a... fetch test C:\Users\mung\Desktop\etc\study\python-gene>git branch * (HEAD detached at origin/master)   master   test1   test2 깃이 잘 쓰면 참 좋은놈인데 어지간히 쓰기가 까다롭다. 처음에 깃을 푸시 성공하는데만 한달정도 걸렸던걸로 기억이 난다.. ㅋㅋㅋ 여담으로  깃 프로필을 가면 아래사진 처럼 보인다. 기여도에 따라서 초록색으로 작은 박스가 채워지는데 저걸 잔디라고 표현을 한다고 합니다 ㅎ 저 사진은 제 깃 기여도 사진입니당 ㅋㅋㅋㅋ 다시 본론으로 돌아와서 ㅋㅋ pull을 하면 깃에 최신 소

[kali linux] sqlmap - post요청 injection 시도

아래 내용은 직접 테스트 서버를 구축하여 테스트 함을 알립니다.  실 서버에 사용하여 얻는 불이익에는 책임을 지지 않음을 알립니다. sqlmap을 이용하여 get요청이 아닌 post요청에 대해서 injection공격을 시도하자. 뚀한 다양한 플래그를 이용하여 DB 취약점 테스트를 진행을 해보려고 한다. 서버  OS : windows 7 64bit Web server : X Server engine : node.js Framework : expresss Use modules : mysql Address : 172.30.1.30 Open port : 6000번 공격자 OS : kali linux 64bit use tools : sqlmap Address : 172.30.1.57 우선 서버측 부터  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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 var  express  =  require( 'express' ); var  app  =  express(); var  mysql  =  require( 'mysql' ); var  ccc  =  mysql.createConnection({     host: '127.0.0.1' ,     user: 'root' ,     post: '3306' ,     password: '*********' ,     database: 'test' }) app.post(