임포트
nsdmodule.py
print("모듈이지롱")
def test(x):
print("이건 함수, 들어온값:", x)
class 한국어도된다:
def __init__(self):
self.msg = "신기하죠?"
호출부
import nsdmodule
nsdmodule.test(1)
obj = nsdmodule.한국어도된다()
obj.msg
호출부 다양한 사례
패키지 호출부
import game
# game 폴더 내 __init__.py 를 찾아 인식한다.
game.version
game.render_test()
Py 호출부1
import game.sound.echo
game.sound.echo.echo_test()
Py 호출부2
from game.sound import echo
echo.echo_test()
Py 호출부3
import game.sound.echo as ec
ec.echo_test()
함수 호출부
from game.sound.echo import echo_test
echo_test()
파서
nsdmodule_lab1.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-kn", "--koreaname", dest="name")
parser.add_argument("-en", "--englishname", dest="eng_name")
# kn, koreaname 쓰고 싶은 키워드를 정의할 수 있다.
# 파서의 인자들을 파싱
args = parser.parse_args()
print(args.name)
print(args.eng_name)
호출부
!python nsdmodule2.py -m "안녕하세요" -lr 0.001
__main__
모듈(파일)을 직접 호출할 때 작동한다.
if __name__ = "__main__":
데코레이터
함수를 인자로 보내서, 함수를 호출한다.
def trace(func): # 호출할 함수를 매개변수로 받음
def wrapper():
print(func.__name__, '함수 시작') # __name__으로 함수 이름 출력
func() # 매개변수로 받은 함수를 호출
print(func.__name__, '함수 끝')
return wrapper # wrapper 함수 반환, 최종실행
# @데코레이터: 자식함수를 실행하기 전에 @에 있는 함수를 먼저 호출해서,
# 특정 감싸는 기능들을 추가한다음에 return되는걸로 실행
@trace
def hello():
print('hello')
@trace # @데코레이터
def world():
print('world')
hello() # 함수를 그대로 호출
world() # 함수를 그대로 호출
yield
def test1():
yield 10
yield 20
a=test1() # 함수를 변수로 꼭 저장해야함 (state 성이 있어야 하니까)
next(a)
> 10
next(a)
> 20
Tags:
클라우드