본문 바로가기

KnowledgeBase

Python : 모든 것은 객체임 그냥 그런 거임.

1. 이터레이터와 제네레이터

PS, 이터레이션이 가능한 객체란, for item in items: 구문에 사용할 수 있는 items

1.1 이터레이터 (클래스)

이터레이션이 가능한 객체 생성용 클래스  : __iter__ (초기값 세팅용으로 self 리턴), __next__(이터레이션시 리턴 값)을 구현하는 클래스로 이터레이션 끝에 도달하면 raise StopIteration 으로 예외 발생시켜주면 됨

1.2 제네레이터 (함수)

이터레이터 만들려면 귀찮으니까 좀 더 편하게 이터레이션이 가능한 객체를 만들어주는 함수 : yield 를 하나 이상 사용하면 제네레이터임. yield 는 return 하고 똑같이 값을 리턴해주는데 차이점은 return은 해당 시점에서 함수 실행을 끝내 버리지만 yield는 해당 시점에 값을 리턴할뿐 객체와 상태값을 유지하고 있음.

1.3 제네레이터 함수 표현식 : 익명함수 처럼 쓰는법

my_list = [1, 3, 6, 10]
a = (x**2 for x in my_list) // a는 이터레이션 가능 객체가 됨

sum(x**2 for x in my_list) // 이런식으로 함수 안에서도 사용 가능

1.4 제네레이터 장점: 이터레이터 클래스 정의보다 간편(코드가 짧다)하고 효율적(리스트 마냥 전체 데이터를 메모리에 올려놓을 필요 없이 그때 그때 필요한 데이터 하나만 올려 놓는다)임

 

2. 클로져 함수(단일 메서드 클래스 대용품)

def print_msg(msg):
# This is the outer enclosing function

    def printer():
# This is the nested function
        print(msg)

    return printer  # this got changed

# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()

중첩된 함수 printer()가 print_msg() scop의 변수를 참조하는 것
즉, 클로져의 생성 조건은
- 함수가 중첩되어 있을 것
- child 함수는 parent함수에서 정의된 변수를 참조할 것
- parent함수는 child 함수를 리턴 할 것

왜쓸까?
- 글로별 변수 사용을 피하고, 데이터 은닉을 제공한다.
- 메서드 한 개 짜리를 비롯해서 소수의 메서드만 필요할때는 클래스보다 클로져가 낫다.

TIP, 클로져 안에서 밖의 변수 값을 수정하려면 밖의 변수 a를 내부에서 nonlocal a 라고 로컬 변수가 아님을 알려주면 된다

3. 데코레이터 함수 : 컴파일 타임에 함수에 기능 추가하는 기능 (클래스의 상속 = 함수의 상속 = 데코레이터 함수)

데코레이터 함수는 인자로 다른 함수를 받아서 이기능 저기능을 덧붙이고 인자로 받은 함수도 호출하는 이너 함수를 정의하고 이 이너 함수를 리턴하는 함수이다.

클래스는 class A를 class B(A) 가 상속 받아서 A의 메서드를 오버라이딩 하고 super() call

함수는 def B(func A) 를 인자로 받아서 def B의 inner 함수 def C에서 이기능 저기능 하고 A() 호출하는 def C를 리턴

쉽게 쓰는법

@make_pretty
def ordinary():
    print("I am ordinary")

// 위에꺼나 밑에꺼나 쎄임 쎄임

def ordinary():
    print("I am ordinary")
ordinary = make_pretty(ordinary)

파라메터받는 함수의 데코레이터 함수

def smart_divide(func):
   def inner(a,b):
      print("I am going to divide",a,"and",b)
      if b == 0:
         print("Whoops! cannot divide")
         return

      return func(a,b)
   return inner

@smart_divide
def divide(a,b):
    return a/b

// 이러면 귀찮으니까

def smart_divide(func):
   def inner(*args, **kwargs):
      print("I am going to divide",args[0],"and",args[1])
      if b == 0:
         print("Whoops! cannot divide")
         return

      return func(*args, **kwargs)
   return inner

// 이려면 똑같음

근데 @이걸로 데코레이터를 중첩시키면 위에있는거부터 밑으로 순으로 실행됨

4. @property 

__abc 처럼 private으로 지정한 변수에 getter (@property), setter (@abc.setter) 메서드 지정

class Celsius:
    def __init__(self):
        pass
    def to_fahrenheit(self):
        return (self._temperature * 1.8) + 32

    @property
    def temperature(self):
        print("Getting value")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

5. 정규표현식

https://www.programiz.com/python-programming/regex

 

Python RegEx (With Examples)

A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For example, ^a...s$ The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s. A pattern defined using RegEx can

www.programiz.com

https://www.lfd.uci.edu/~gohlke/pythonlibs/#jpype

 

Python Extension Packages for Windows - Christoph Gohlke

by Christoph Gohlke, Laboratory for Fluorescence Dynamics, University of California, Irvine. Updated on 9 March 2020 at 05:31 UTC. This page provides 32- and 64-bit Windows binaries of many scientific open-source extension packages for the official CPython

www.lfd.uci.edu

https://data-flair.training/blogs/machine-learning-datasetshttps://data-flair.training/blogs/python-tutorials-home/

파이썬 패키지 오프라인 설치

https://dydtjr1128.github.io/python/2020/04/27/Python-offline-install.html

 

Python 파일 오프라인 설치 - dydtjr1128's Blog

Install python files offline 오프라인/폐쇄망 환경에서는 특정 라이브러리를 설치하기 위해서는 외부 컴퓨터에서 다운로드 받아 와야 합니다. 다음과 같이...

dydtjr1128.github.io

오프라인/폐쇄망 환경에서는 특정 라이브러리를 설치하기 위해서는 외부 컴퓨터에서 다운로드 받아 와야 합니다.

다음과 같이 간단한 명령으로 특정 라이브러리에 대한 목록 및 다운로드를 진행 할 수 있습니다.

  1. 원하는 라이브러리 설치(ex.pip install pylint)
  2. 다운로드 목록 및 다운로드 내용을 가져올 폴더로 이동(cmd/bash 이용)
  3. 설치된 라이브러리 목록 파일로 저장

    python -m pip freeze > requirements.txt

  4. 설치된 기록된 파일명 라이브러리들 다운로드

    python -m pip download -r .\requirements.txtPytho

  5. 이 폴더를 통째로 오프라인에서 설치할 컴퓨터로 복사

다운로드 받은 파일들을 옮겨서 그 위치에서 파이썬을 실행 후 다음 명령어를 실행합니다.

python -m pip install --no-index --find-links="./" -r .\requirements.txt

위의 명령어로 txt에 기록된 라이브러리들을 쉽게 설치 할 수 있습니다.