기본 콘텐츠로 건너뛰기

[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   

[python] getter, setter대신 @property, @setter를 사용하자

파이썬에서는 getter와 setter를 쓰는것을 권장하지 않는다 대신 @property와 @setter키워드가 존재한다. p.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Mung(object):     def __init__(self):         self._mung = 1         def get_mung(self):         return self._mung       def set_mung(self, value):         self._mung = value   mung = Mung() print(mung.get_mung()) mung.set_mung(10) print(mung.get_mung()) cs $python p.py >>> 1 10 기존의 getter와 setter를 쓴다면 위와 같이 사용을 할 것이다. 근데 파이썬에서는 위처럼 쓰는 코드를 권장하지 않는다. p.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Mung(object):          def __init__(self):         self._mung = 1                @property     def mung(self):         return self._mung         @mung.setter     def mung(self, value):         self._mung = value   mung = Mung() print(mung.mung) mung.mung=10 print(mung.mung) cs $pytho

[python] observer pattern

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 class  Observer(object):      def  __init__(self):         self.a  =  []      def  register(self, listener):         self.a.append(listener)      def  show(self):          for  i  in  self.a:             isListener  =  isinstance(i, Listener1)              print (isListener) class  Listener1():      def  __init__(self, text ):         self.text  =  text      def  text_show(self):          print (self.text) ob  =  Observer() listener1  =  Listener1( 'text1' ) listener2  =  Listener1( 'text2' ) listener3  =  Listener1( 'text3' ) ob.register(listener1) ob.register(listener2) ob.register(listener3) ob.show() Colored by Color Scripter cs isinstance함수는 파이썬 내장 함수이다.  타입을 검사를 하여 false, true를 반환을 해준다 위코드를

[python] try-except, if ~else, 내장모듈 밴치마킹(benchmarking)

이번에는 성능 테스트를 해보려고 한다. 에러를 발생을 시켜 catch부분에서 처리를 하는 방식과, 조건분기, 내장 모듈 사용이 얼마나 걸리는지 테스트를 하려고 한다. 똑같은 값이 얼마나 있는지 카운팅을 해주는 함수이다. 1 2 3 4 5 6 7 8 9 import  time def  time_check(func):      def  new_func():         start  =  time.time()         func()         result  =  time.time()  -  start          print (result)      return  new_func cs 우선 데코레이터로 만들어질 시간 체크 부분이다. 1 2 3 4 5 6 7 8 9 10 #키가 있는지 없는지 검사 후 카운팅 @time_check def  frequency_test1():     Dictionary = dict()      for  i  in   range ( 10000 ):          if  i  in  Dictionary.keys():             Dictionary[i] + = 1          else :             Dictionary[i] = 1      return  Dictionary cs 1 2 3 4 5 6 7 8 9 10 #에러 발생후 카운팅 @time_check def  frequency_test2():     Dictionary = dict()      for  i  in   range ( 10000 ):          try :             Dictionary[i] + = 1          except  KeyError:

[python] python에서 namespace를 써야하나??

파이썬에서는  @staticmethod 를 이용하여 네임스페이스처럼 구현을 할 수가 있다 근데 파이썬에서 꼭 네임스페이스를 써야하나라는 생각이 들기시작 했다(자고 일어나다가 왜 이런생각이 난거지 참....) namespace란?  - namespace란 함수 이름이 같아도 쓸수 있게 함수마다 공간을 할당을 해주는 것을 의미한다. 네임스페이스를 쓰는 목적만 보면 오 좋은거네? 라고 생각을 할 수가 있다. 그런데 네임스페이스를 쓰는 c++과 python의 모듈 혹은 헤더파일이 작동 방식이 매우 다르다. c++ 헤더파일 작동 방식 그리고 namespace (IDE를 설치 되어있지 않아 우분투에서 vim + gcc로 테스트 진행 - 도커를 이러려고 설치한건 아닌데 아무쪼로 잘 쓰는중 ㅋㅋㅋㅋㅋㅋㅋ) 우선 c, c++에서 헤더파일이 어떻게 작동하는지 알아보겠다. 1 2 3 4 5 6 #include   < stdio.h >   int  main( void ){       printf ( "hello world\n" );       return   0 ;  } cs 프로그래밍을 배웠으면 누구나 다 쳐봤다는 hello world! 해당 print부분을 헤더로 분할을 해보겠다. test.cpp 1 2 3 4 5 6 7 8 9 #include   < stdio.h > #include   "pjt.h" int  main( void ){          printf ( "hello world\n" );         show();          return   0 ; } Colored by Color Scripter cs pjt.h 1 void  show()