라벨이 메소드인 게시물 표시

파이썬[Python]: datetime - date 메서드

datetime 모듈 - datetime 클래스 - date 메서드(method) /// 설명 '년-월-일'을 반환합니다. ※ 형식 datetime.date() reference https://docs.python.org/3/library/datetime.html#module-datetime /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import  datetime   year  =  datetime.datetime.utcnow().year month  =  datetime.datetime.utcnow().month day  =  datetime.datetime.utcnow().day hour  =  datetime.datetime.utcnow().hour minute  =  datetime.datetime.utcnow().minute second  =  datetime.datetime.utcnow().second microsecond  =  datetime.datetime.utcnow().microsecond   # KTC test_timezone  =  datetime.timezone(datetime.timedelta(hours = 9 ),  'KST' )   test_dt  =  datetime.datetime(year = year, month = month, day = day, hour = hour, minute = minute,                             second = second, microsecond = microsecond, tzinfo = test_timezone, fold = 0 )   print (test_dt.date())   # 2022-01-04   Colored by Color Scripter cs * 실행환경: Microsoft Windows 10 Homes * 인터프리터: 파이썬(Pytho

파이썬[Python]: 내장함수 - super 함수

내장함수 - super 함수(function) /// 설명 상위(parent) 클래스나 등위(sibling) 클래스의 메서드 호출을 위임하는 객체(중계기능)를 반환합니다.(속성(attribute)에도 사용할 수 있습니다.) super() 는 __mro__ 에서 반환하는 우선순위 중, 상위 클래스에서 처음나오는 메서드를 호출하며, 모든 상위 클래스에 메서드가 존재하지 않으면 오류를 발생시킵니다. ex) class A -> class B -> class C -> object class A에서 super()를 사용할 경우 B, C, object 순으로 탐색을 하고, 그 중 가장 먼저 나오는 메서드를 호출합니다. 만약 없으면 오류를 발생시킵니다. 클래스 내부에서 사용시 상위 클래스가 단일하다면, super().method() 형태로 사용하시면 되고, 상위 클래스가 둘 이상이라면, super(type, object).method() 형태로 사용하시면 됩니다. 참고: __mro__ ※ 형식 class super([type[, object-or-type]]) reference https://docs.python.org/3/library/functions.html /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class  A(object):   # base class A      def  a( self ):          print ( 'test A' )     class  B(A):      def  a( self ):          print ( 'test B' )     if  issubclass(B, A):      print (A.__mro__)   # (<class '__main__.A'>, <class 'object'>)      print (B.__m

파이썬[Python]: 내장함수 - type 함수

내장함수 - type 함수(function) /// 설명 객체의 타입을 반환하며, object.__class__ 와 같은 값을 가집니다. 인자 3 개를 사용할 경우에는 새로운 객체를 생성합니다. 참고: isinstance() ※ 형식 class type(object) class type(name, bases, dict, **kwds) reference https://docs.python.org/3/library/functions.html /// 예제 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 import  types     def  func_a():      pass     class  A:      pass     test_1  =   1 test_2  =   'string' test_3  =  [ 1 ,  2 ,  3 ,  4 ,  5 ] test_4  =  lambda:  1   print (type(test_1))   # <class 'int'> print (type(test_2))   # <class 'str'> print (type(test_3))   # <class 'list'> print (type(test_4))   # <class 'function'> print (type(func_a))   # <class 'function'> print (type(A()))   # <class '__main__.A'> print (test_1.__class__)   # <class 'int'> print (test_2.__class__)  

파이썬[Python]: kivyMD - run 메서드

이미지
kivymd.app 모듈 - MDApp 클래스 - run 메서드(method) /// 설명 (kivy + kivyMD) 독립실행방식으로 앱(MDapp)을 실행합니다. 참고: kivyMD 모듈 목록 ※ 형식 app.run() reference https://kivymd.readthedocs.io/en/latest/themes/material-app/ /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import  kivy   kivy.require( '2.0.0' )   from  kivy.core.window  import  Window   from  kivymd.app  import  MDApp   Window.clearcolor  =  ( 0 ,  0 ,  0 ,  1 ) Window.size  =  ( 563 ,  1001 ) Window.top, Window.left  =   30 ,  700     class  FantasticApp(MDApp):      def  build( self ):          return   None     FantasticApp().run()   Colored by Color Scripter cs /// 출력 * 실행환경: Microsoft Windows 10 Homes * 인터프리터: 파이썬(Python 3.9) – 당신을 응원합니다. –

파이썬[Python]: functools - cache 함수

functools 모듈 - cache 함수(function) /// 설명 최근의 함수호출을 저장하고, 그 저장된 내용을 사용합니다. ※ 형식 @functools.cache(user_function) reference https://docs.python.org/3/library/functools.html#functools.lru_cache /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import  functools     @functools.cache def  factorial(n):      return  n  *  factorial(n - 1 )  if  n  else   1     # cached print (factorial( 10 ))   # 3628800   # just looks up cached value result print (factorial( 3 ))   # 6   # makes five new recursive calls print (factorial( 15 ))   # 1307674368000   Colored by Color Scripter cs * 실행환경: Microsoft Windows 10 Homes * 인터프리터: 파이썬(Python 3.9) – 당신을 응원합니다. –

파이썬[Python]: filecmp - cmp 함수

filecmp 모듈 - cmp 함수(function) /// 설명 두 파일을 비교합니다. 같으면 True, 그렇지 않으면 False 를 반환합니다. shallow 인자가 True 이고, os.stat() 시그너쳐(파일타입, 크기, 수정한 날짜)가 같으면 같은 파일로 여깁니다. 그렇지않고 크기와 내용이 다르면 다른 파일로 간주됩니다. ※ 형식 filecmp.cmp(f1, f2, shallow=True) reference https://docs.python.org/3/library/filecmp.html#module-filecmp /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 import  filecmp   # __init__1.py and __init__2.txt '' ' import kivy kivy.require(' 2. 0. 0 ') from kivy.app import App from kivy.core.window import Window from kivy.uix.settings import Settings from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label ' ''     # sizes or contents print (filecmp.cmp( './__init__1.py' ,  './__init__2.txt' , shallow = False ))   # True   # os.stat() signatures (file type, size, and modification time) ---> I expected 'False' print (filecmp.cmp( './__init__1.py' ,  &

파이썬[Python]: 내장함수 - vars 함수

내장함수 - vars 함수(function) /// 설명 모듈, 클래스, 인스턴스 또는 다른 어떤 객체의 __dict__ 값을 반환합니다. ※ 형식 vars([object]) reference https://docs.python.org/3/library/functions.html /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import  __main__     class  A:      def  __init__( self , string):          self .string  =  string     print (vars())   # {'__name__': '__main__', '__doc__': None, '__package__': None, ... print (locals())   # {'__name__': '__main__', '__doc__': None, '__package__': None, ... print (vars(__main__))   # {'__name__': '__main__', '__doc__': None, '__package__': None, ... print (__main__.__dict__)   # {'__name__': '__main__', '__doc__': None, '__package__': None, ...   a  =  A( 'This is a string' ) print (vars(a))   # {'string': 'This is a string'} print (a.__dict__)   # {'string': 'This is a string'}   Col

파이썬[Python]: 내장함수 - __getattr__ 메서드

파이썬(Phthon): 내장함수 - __getattr__ 메서드(method) /// 설명 기본 속성에 접근할 수 없을 경우 호출 됩니다. 반환 값은 (변형된)속성값이어야 합니다. 어떤 속성이든(존재하던, 존재하지 않던) 접근할 경우 __getattribute__() 호출, 없을 경우 __getattr__() 호출합니다. __getattribute__() 은 일반적 방식입니다. 이 방식이 작동하지 않으면 __getattr__()는 __dict__() 를 다시 찾아봅니다. 그리고 속성이 있다면 반환하고 없으면 (변형된)반환값을 표현하거나 오류를 발생시킵니다. 참고: __getattribute__() ※ 형식 object.__getattr__(self, name) reference https://docs.python.org/3/reference/datamodel.html /// 예제 1 2 3 4 '' '     Just a moment... if this method has no special work to do, it is useless ' ''   Colored by Color Scripter cs * 실행환경: Microsoft Windows 10 Homes * 인터프리터: 파이썬(Python 3.9) – 당신을 응원합니다. –

파이썬[Python]: 내장함수 - __getattribute__ 메서드

파이썬(Phthon): 내장함수 - __getattribute__ 메서드(method) /// 설명 클래스의 인스턴스에서 속성(attribute)에 접근하고자 할 경우 호출 됩니다. 클래스의 속성을 직접 반환하면 recursion 이 발생합니다. object.__getattribute__(self, name) 필요 ex) a.string -> __getattribute__ 호출 -> return self.string -> __getattribute__ 호출 -> return self.string -> ... 참고: __getattr__() ※ 형식 object.__getattribute__(self, name) reference https://docs.python.org/3/reference/datamodel.html /// 예제 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class  A:      def  __init__( self , string):          self .string  =  string        def  __getattribute__( self , name):          try :             attribute  =   super (A,  self ).__getattribute__(name)              return  attribute          except  AttributeError  as  e:              print (e)     a  =  A( 'This is a string' ) print (a.__dict__)   # {'string': 'This is a string'} print (a.string)   # This is a string print (getattr(a,  'string' ))   # This is a 

파이썬[Python]: 내장함수 - __bool__ 메서드

파이썬(Phthon): 내장함수 - __bool__ 메서드(method) /// 설명 True 값을 테스트하고 내장함수 bool() 을 구현하기 위해 호출 됩니다. 참고: __len__() ※ 형식 object.__bool__(self) reference https://docs.python.org/3/reference/datamodel.html /// 예제 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 class  A:      def  __init__( self , a):          self .a  =  a        def  __bool__( self ):          return  bool( self .a)     print (A( '' ).__bool__())   # False print (A( 'string' ).__bool__())   # True   a  =  A( '' ) print (bool(a))   # False a  =  A( 'string' ) print (bool(a))   # True     # if no __bool__(), then __len__() will be used.(fall back) class  B:      def  __init__( self , a):          self .a  =  a        def  __len__( self ):          return   len ( self .a)     a  =  B( '' ) print (bool(a))   # False a  =  B( 'string' ) print (bool(a))   # True     # if defines neither __bool__() nor __

파이썬[Python]: numpy - asanyarray 함수

numpy 모듈 - asanyarray 함수(function) /// 설명 입력을 배열(ndarray)로 변환합니다.(ndarray subclass를 허용합니다.) a : 입력 데이터 입니다.(입력: 리스트, 튜플, ndarray) dtype : 출력할 배열의 데이터 형식입니다. 기본값으로 입력 데이터 형식을 따릅니다. order : 결과물의 메모리 저장 형식을 결정합니다. 'C'는 C언어 형식, 'F'는 포트란 형식입니다. 'A'는 prototype이 포트란 연속(Fortran contiguous)이면 'F', 아니면 'C'로 결정됩니다. 'K'(keep)는 입력 a 의 형식을 보존합니다. 기본값은 'K' 입니다. like : Numpy 배열이 아닌 형태로 생성하는 것을 허용합니다.(__array_function__ 프로토콜을 사용합니다.) ※ 형식 numpy.asanyarray(a, dtype=None, order=None, *, like=None) reference https://numpy.org/devdocs/reference/generated/numpy.asanyarray.html /// 예제 array-like 1 2 3 4 5 6 7 8 9 10 11 12 import  numpy  as  np   test  =  np.array([( 1. 0 ,  2 ), ( 3. 0 ,  4 )], dtype = 'f4,i4' ) print (test)   # [(1., 2) (3., 4)] print (np.asarray(test)  is  test)   # True print (np.asanyarray(test)  is  test)   # True   test  =  np.array([( 1. 0 ,  2 ), ( 3. 0 ,  4 )], dtype = 'f4,i4' ).view(np.recarr

파이썬[Python]: numpy - asarray 함수

numpy 모듈 - asarray 함수(function) /// 설명 입력을 배열(ndarray)로 변환합니다. a : 입력 데이터 입니다.(입력: 리스트, 튜플, ndarray) dtype : 출력할 배열의 데이터 형식입니다. 기본값으로 입력 데이터 형식을 따릅니다. order : 결과물의 메모리 저장 형식을 결정합니다. 'C'는 C언어 형식, 'F'는 포트란 형식입니다. 'A'는 prototype이 포트란 연속(Fortran contiguous)이면 'F', 아니면 'C'로 결정됩니다. 'K'(keep)는 입력 a 의 형식을 보존합니다. 기본값은 'K' 입니다. like : Numpy 배열이 아닌 형태로 생성하는 것을 허용합니다.(__array_function__ 프로토콜을 사용합니다.) ※ 형식 numpy.asarray(a, dtype=None, order=None, *, like=None) reference https://numpy.org/devdocs/reference/generated/numpy.asarray.html /// 예제 array-like 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 import  numpy  as  np   array  =  (( 1 ,  2 ), ( 3 ,  4 )) print (array) # ((1, 2), (3, 4))   test_np  =  np.asarray(array) print (test_np) # [[1 2] #  [3 4]]   print (array  is  test_np)   # False   list  =  [[ 1 ,  2 ], [ 3 ,  4 ]] print (list)   # [[1, 2], [3, 4]]   test_np  =  np.asarray(list)