티스토리 뷰
INTRO
함수와 메서드를 구분하면 mothod는 class의 object로 호출되며 .function() 형태로 작동
function()은 def f(): return 형태로 구성되며 직접 만든 형태를 사용자 정의 함수라 구분
함수(function), 메서드(method : Class 내 함수)를 .py로 저장하여 만든 파일을 module로 구분
package(패키지) : 하나 이상 module의 directory(or foler) 묶음 또는 library 배포 관점의 의미
하나 이상의 package와 module 묶음을 library로 구분
(참고) import 방법 : library, package, module, function, class
1. method
Class module을 만들어 method 사용법을 익혀본다.
pyTest dir에서 myClass dir을 만들고 그 하위에 exClass1.py를 생성한다.
Tree 구조 : 현재 pyTest dir에서 tree 명령어로 확인, macOS terminal의 tree 명령어는 brew 설치 후 사용 가능
.
├── myClass
│ └── exClass1.py
├── test0.py
├── test1.py
├── test2.py
├── test3.py
├── test4.py
├── test5.py
├── test6.py
├── test7.py
├── test8.py
└── test9.py
python code : pyTest/myClass/exClass1.py
class 네이밍은 CamelCase를 사용, __init__는 생성자, __del__은 소멸자, sign_up은 method 함수
class Person:
def __init__(self,name):
self.name = name
print("The name is initialized to '{}'".format(name))
def sign_up(self,birth,sex):
self.birth = birth
self.sex = sex
print("'{}' has signed up".format(self.name))
birth_splt = birth.split('.')
print("Birth-day:{}. {}. {}".format(birth_splt[0],birth_splt[1],birth_splt[2]))
print("sex: {}".format(sex))
def __del__(self):
print("Object of {} is deleted".format(self.name))
---- Terminal : pyTest directory에서 python3 REPL Shell에서 결과 확인, SublimeText REPL 결과와 다름 ----
참고 : python3 REPL Shell에서 엔터(줄띄움)는 나타나지 않음. 결과 구분을 위해 임의로 넣은 것임
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from myClass.exClass1 import Person
>>> user = Person('persona')
The name is initialized to 'persona'
>>> print(user)
<myClass.exClass1.Person object at 0x10c1e97c0>
>>> print(type(user))
<class 'myClass.exClass1.Person'>
#### method 사용방법 : object.method(매개변수1, 매개변수2)
>>> user.sign_up('2020.12.25','male')
'persona' has signed up
Birth-day:2020. 12. 25
sex: male
>>> print(type(user.sign_up('2020.12.25','male')))
'persona' has signed up
Birth-day:2020. 12. 25
sex: male
<class 'NoneType'>
>>> del(user)
Object of persona is deleted
>>> print(user)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'user' is not defined
************ (참고) import 방법 : library, package, module, function, class ************
from directory.module import function/package
ex> import 예제 : example_import.py
example_import.py
import os
import sys
import numpy
from myfun.mytestfun1 import person
from myClass.exClass1 import Person
print("지역 심볼 테이블(current namespace) 보기 : dictionary로 뿌려줌")
print(locals())
print('\n\n')
print("원하는 심볼 선택 보기 : dic 'key'의 <value>로 뿌려줌")
print(" 'os' : module \n{}\n".format(locals()['os']))
print(" 'sys' : module, bulit-in \n{}\n".format(locals()['sys'],'\n'))
print(" 'numpy' : 3rd party package/module \n{}\n".format(locals()['numpy'],'\n'))
print(" 'person' : function \n{}\n".format(locals()['person']))
print(" 'Person' : class \n{}".format(locals()['Person']))
---- SublimeText python Run example_import.py ----
지역 심볼 테이블(current namespace) 보기 : dictionary로 뿌려줌
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10b5acca0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/jiwonlee/py_design_tool/pyTest/test11.py', '__cached__': None, 'os': <module 'os' from '/usr/local/Cellar/python@3.9/3.9.1_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>, 'sys': <module 'sys' (built-in)>, 'numpy': <module 'numpy' from '/usr/local/lib/python3.9/site-packages/numpy/__init__.py'>, 'person': <function person at 0x1168618b0>, 'Person': <class 'myClass.exClass1.Person'>}
원하는 심볼 선택 보기 : dic 'key'의 <value>로 뿌려줌
'os' : module
<module 'os' from '/usr/local/Cellar/python@3.9/3.9.1_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py'>
'sys' : module, bulit-in
<module 'sys' (built-in)>
'numpy' : 3rd party package/module
<module 'numpy' from '/usr/local/lib/python3.9/site-packages/numpy/__init__.py'>
'person' : function
<function person at 0x1168618b0>
'Person' : class
<class 'myClass.exClass1.Person'>
***Repl Closed***
*******************************************************************************************
2. function
사용자 지정 함수 def를 module 내에서 사용하고 myfun dir에 module을 저장하여 import 후 사용해본다.
pyTest dir에서 myfun dir을 만들고 그 하위에 mytestfun1.py를 생성한다.
실행 파일 pyTest/test10.py와 module pyTest/myfun/mytestfun1.py 2개의 파일이 필요
Tree 구조 : 현재 pyTest dir에서 tree 명령어로 확인
.
├── myClass
│ └── exClass1.py
├── myfun
│ └── mytestfun1.py
├── test0.py
├── test1.py
├── test10.py
├── test2.py
├── test3.py
├── test4.py
├── test5.py
├── test6.py
├── test7.py
├── test8.py
└── test9.py
python code : pyTest/myfun/mytestfun1.py
function 안에 function을 다루는 경우 보다는 사용자 정의 형태로 module을 만들고 import해서 다루는 게 좋다. 예시는 예시일 뿐...
function module의 매개변수의 갯수는 main function인 test10.py에서 호출 시 맞춰야함
return 에서 변수(object)를 지정해서 돌려줄 수 있다. 이 때 object type은 module script를 수행 후 type을 따름
return 에서 변수(object)를 지정하지 않으면 "None"을 뱉어낸다.
def person(name,birth,sex):
print("-->person function")
print("Use '{}' for login".format(name))
def sign_up(name,birth,sex):
print("\n-->sign_up function")
print("'{}' has signed up".format(name))
birth_splt = birth.split('.')
print("Birth-day:{}. {}. {}".format(birth_splt[0],birth_splt[1],birth_splt[2]))
print("sex: {}\n".format(sex))
sign_up(name,birth,sex)
return name
def create_post(pname):
print("\n-->create_post function")
return print("'{}'' is created".format(pname))
python code : pyTest/test10.py
del()은 별도로 지정하지 않아도 내장함수로 작동한다.
지역변수(local variable) 확인을 위해 locals() 함수로 확인 가능하다.
1행 import로 선언된 person은 <function person ... > type임을 알 수 있다.
2행 user에 할당된 perona는 dic 변수로 저장됨을 알 수 있다.
from myfun.mytestfun1 import person
user = person('persona','2020.12.25','male')
print("'{}' type : {}\n".format(user,type(user)))
print("function import : 'person'\n{}\n".format(locals()))
del(user)
print("delete object : 'user'\n{}\n".format(locals()))
from myfun.mytestfun1 import create_post
post = create_post('persona_post')
print("'{}' type : {}\n".format(post,type(post)))
---- SublimeText python Run test10.py ----
-->person function
Use 'persona' for login
-->sign_up function
'persona' has signed up
Birth-day:2020. 12. 25
sex: male
'persona' type : <class 'str'>
function import : 'person'
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x106eecc70>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '~/pyTest/test10.py', '__cached__': None, 'person': <function person at 0x1070c1820>, 'user': 'persona'}
delete object : 'user'
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x106eecc70>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '~/pyTest/test10.py', '__cached__': None, 'person': <function person at 0x1070c1820>}
-->create_post function
'persona_post'' is created
'None' type : <class 'NoneType'>
***Repl Closed***
'python > Lecture' 카테고리의 다른 글
python 기초 #7 : File Handling - csv, excel(xlsx) (0) | 2021.03.03 |
---|---|
python 기초 #6 : File Handling - txt (0) | 2021.03.03 |
python 기초 #4 : Code Block(제어문 : 조건문/반복문) (0) | 2021.02.25 |
python 기초 #3 : Data-type Handling(자료형 다루기) (0) | 2021.02.24 |
python 기초 #2 : Data-type(자료형) (0) | 2021.02.23 |
- Total
- Today
- Yesterday
- analysis
- DAQ
- Python
- COVID-19
- Templates
- git
- github
- 코로나19
- 확진
- ERP
- raspberrypi
- Raspberry Pi
- arduino
- 자가격리
- pyserial
- 코로나
- Model
- Django
- r
- Regression
- DS18B20
- SSH
- 라즈베리파이
- template
- MacOS
- server
- vscode
- CSV
- sublime text
- Pandas
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |