Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

히바리 쿄야 와 함께 하는 Developer Cafe

[4일차] DO IT 점프투파이썬 /p183 ~ p261/ 05.클래스,패키지,예외처리 본문

Python

[4일차] DO IT 점프투파이썬 /p183 ~ p261/ 05.클래스,패키지,예외처리

TWICE&GFRIEND 2021. 2. 20. 20:45
D:\Python>mkdir mymod

D:\Python>move mod2.py mymod
        1개 파일을 이동했습니다.

D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
>>> sys.path.append("D:\Python\mymod")
>>> sys.path
['', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\SONG\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'D:\\Python\\mymod']
>>> import mod2
>>> print(mod2.add(3,4))
7


D:\Python>set PYTHONPATH=D:\Python\mymod

D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mod2
>>> print(mod2.add(3,4))
7



D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import game.sound.echo
>>> game.sound.echo.echo_test()
echo
>>> from game.sound import echo
>>> echo.echo_test()
echo
>>> from game.sound.echo import echo_test
>>> echo_test()
echo
>>> import game
>>> game.sound.echo.echo_test()
echo
>>> import game.sound.echo.echo_test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'game.sound.echo.echo_test'; 'game.sound.echo' is not a package

>>> from game.sound import*
>>> echo.echo_test()
echo

패키지에 포함된 디렉터리에 __init__.py 파일이 없으면 패키지로 인식되지 않는다..

>>> from game.graphic.render import render_test
>>> render_test()
render
echo

# #render.py
# from game.sound.echo import echo_test
# def render_test():
#     print("render")
#     echo_test()
    
#render.py
from ..sound.echo import echo_test
def render_test():
    print("render")
    echo_test() 

.. 무모 디렉토리
.  현재 디렉토리

relative 접근자는 render.py 처럼 모듈 안에서만 사용해야 함 



예외처리 

f = open("나 없는 파일",'r')
Traceback (most recent call last):

  File "<ipython-input-1-3aa360813f0e>", line 1, in <module>
    f = open("나 없는 파일",'r')

FileNotFoundError: [Errno 2] No such file or directory: '나 없는 파일'


4 / 0
Traceback (most recent call last):

  File "<ipython-input-2-87ac9c94a8c2>", line 1, in <module>
    4 / 0

ZeroDivisionError: division by zero


a = [1,2,3]

a[4]
Traceback (most recent call last):

  File "<ipython-input-4-ed40d1f49c42>", line 1, in <module>
    a[4]

IndexError: list index out of range


try:
   ....
except [발생오류[as 오류 메세지 변수]]:
   ....
   
except[발생오류 [as 오류 메세지 변수]]:

오류 종류에 상관없이 오류가 발생하면  except 블록 수행

try:
   ....
except 발생오류 as 오류 메세지 변수:
   ....
   


try:
    4/0
except ZeroDivisionError as e:
    print(e)
    
division by zero


try:
	...
except 발생 오류 1
    ...
except 발생 오류 2
	...
    
try:
    a = [1,2]
    print(a[3])
    4/0
except ZeroDivisionError:
    print("0으로 나눌 수 없습니다.")
except IndexError:
    print("인덱싱 할 수 없습니다.")
    
인덱싱 할 수 없습니다.

먼저 발생한 오류부터 처리하기 때문에 인덱싱 오류 메세지가 출력된다.



try:
    a = [1,2]
    print(a[3])
    4/0
except ZeroDivisionError as e:
    print(e)
except IndexError as e:
    print(e)
    
list index out of range


try:
    a = [1,2]
    print(a[3])
    4/0
except (ZeroDivisionError,IndexError) as e:
    print(e)
    
list index out of range


try:
    f = open("없는 파일",'r')
except FileNotFoundError:
    pass


try:
    f = open("없는 파일",'r')
except FileNotFoundError:
    pass
    

class Bird:
    def fly(self):
        raise NotImplementedError


class Eagle(Bird):
    pass

eagle = Eagle()

eagle.fly()
Traceback (most recent call last):

  File "<ipython-input-13-01d103cfb97d>", line 1, in <module>
    eagle.fly()

  File "<ipython-input-10-e8d1e4453b08>", line 3, in fly
    raise NotImplementedError

NotImplementedError

Eagle 클래스에서 fly 라는 함수를 구현하지 않았기 때문에 에러발생

상속받는 클래스에서 함수를 재구현 하는 것을 메소드 오버라이딩 이라고 한다.




class Eagle(Bird):
    def fly(self):
        print("very fast")
        

eagle = Eagle()

eagle.fly()
very fast


class MyError(Exception):
    pass
    

def say_nick(nick):
    if nick == '바보':
        raise MyError()
    print(nick)
    

say_nick("천사")
천사

say_nick("바보")
Traceback (most recent call last):

  File "<ipython-input-29-e2fcd6d5b76b>", line 1, in <module>
    say_nick("바보")

  File "<ipython-input-27-01df6befaf0c>", line 3, in say_nick
    raise MyError()

MyError


try:
    say_nick("천사")
    say_nick("바보")
except MyError:
    print("허용되지 않는 별명입니다.");
    
천사
허용되지 않는 별명입니다.


try:
    say_nick("천사")
    say_nick("바보")
except MyError as e:
    print(e)
    
천사


class MyError(Exception):
    def __str__(self):
        return "허용되지 않는 별명입니다."
        
abs(3) -> 절대값 
Out[33]: 3

abs(-3)
Out[34]: 3

abs(-1.2)
Out[36]: 1.2


all(x) 반복가능한 자료형 x 를 입력 인수로 받으며
x 가 모두 참이면 True 거짓이 하나라도 있으면 False 

all([1,2,3])
Out[37]: True

all([1,2,3,0])
Out[38]: False  요소 0은 거짓이므로 false 호출됨


any(x) x중 하나라도 참이 있으면 True x가 모두 거짓일 경우 False

any([1,2,3,0])
Out[39]: True

any([0,""])
Out[40]: False  -> 모두 거짓이기 때문에 false 


chr(x) 아스키 코드 값을 입력받아 코드에 해당하는 문자를 출력하는 함수

chr(97)
Out[41]: 'a'

chr(48)
Out[42]: '0'


dir 객체가 자체적으로 가지고 있는 변수나 함수를 보여준다.

dir([1,2,3])
Out[43]: 
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

dir({'1':'a'})
Out[44]: 
['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']
 
 
divmod(a,b) 2개의 숫자를 입력 받음 a를 b로 나눈 몫과 나머지를 튜플 형태로 돌려주는 함수
 
divmod(7,3)
Out[45]: (2, 1)

7 // 3
Out[46]: 2

7 % 3
Out[47]: 1


enumerate 열거하다 자료형(리스트,튜플,문자열)을 입력받아 인덱스 값을 포함하는
enumerate 객체로 돌려준다

for i, name in enumerate(['body','foo','bar']):
    print(i, name)
    
0 body
1 foo
2 bar



eval(expression) 실행 가능한 문자열(1+2,'hello'+'a'같은것) 입력받아 문자열을 실행한
결과값을 돌려줌


eval('1+2')
Out[49]: 3

eval("'hello' + 'a'")
Out[50]: 'helloa'

eval('divmod(4,3)')
Out[51]: (1, 1)


eval 함수는 파이썬 함수나 클래스를 동적으로 실행하고 싶을때 사용


filter  첫번째 인수 함수이름 두번째 인수 반복 가능한 자료형 요소가 첫번째 인수인 
함수에 입력되었을때 반환값이 참인 것만 묶어서 돌려준다


#positive.py
def positive(l):
    result = []
    for i in l:
        if i > 0:
            result.append(i)
        return result

print(positive([1,-3,2,0,-5,6]))

1,2,6


def positive(x):
    return x > 0

print(list(filter(positive,[1,-3,2,0,-5,6])))


def negative(y):
    return y < 0

print(list(filter(negative,[1,-3,2,0,-5,6])))


list(filter(lambda x:x > 0,[1,-3,2,0,-5,6]))
Out[59]: [1, 2, 6]


hex -> 16진수

hex(234)
Out[60]: '0xea'

hex(3)
Out[61]: '0x3'


id(object) 객체를 입력받아서 객체의 고유 주소 값(레퍼런스) 로 돌려주는 함수

a = 3

id(3)
Out[63]: 140727098309760

id(a)
Out[64]: 140727098309760

b = a

id(b)
Out[66]: 140727098309760

모두 같은 객체를 가리킨다.

id(4) 다른 객체 이기 때문에 다른 고유 주소값이 나옴
Out[67]: 140727098309792


input([prompt]) 사용자를 입력받는 함수

a = input()

hi

a
Out[69]: 'hi'

b = input("Enter: ")

Enter: hi

b
Out[71]: 'hi'



int 정수

int('3')
Out[72]: 3

int(3.4)
Out[73]: 3

int('11',2)
Out[74]: 3

int('1A',16)
Out[75]: 26



isinstance(object, class) 첫번째 인수 인스턴스, 두번째 인수 클래스 이름을 받는다
입력 받은 인스턴스가 그 클래스의 인스턴스 인지 판단 참이면 True 거짓 False 


class Person: pass

a = Person()

isinstance(a, Person)
Out[78]: True

b = 3

isinstance(b, Person)
Out[80]: False


len(x) 입력값 x의 길이(요소의 전체 갯수) 돌려주는 함수

len("python")
Out[81]: 6

len([1,2,3])
Out[82]: 3

len((1,'a'))
Out[83]: 2



list(x) 반복 가능한 자료형 x 를 입력 받아서 리스트로 돌려주는 함수

list("python")
Out[84]: ['p', 'y', 't', 'h', 'o', 'n']

list((1,2,3))
Out[85]: [1, 2, 3]

a = [1,2,3]

b = list(a)

b
Out[88]: [1, 2, 3]



map(function, iterable) 함수 function와 반복가능한 iterable 자료형을 입력으로 받음
map은 입력 받은 자료형의 각 요소를 함수가 수행한 결과를 묶어서 돌려주는 함수


#two_times.py
def two_times(numberList):
    result = []
    for number in numberList:
        result.append(number*2)
    return result
    

result = two_times([1,2,3,4])
print(result)

[2, 4, 6, 8]


def two_times(x): return x*2

list(map(two_times, [1,2,3,4]))
Out[91]: [2, 4, 6, 8]

list(map(lambda a: a*2, [1,2,3,4]))
Out[92]: [2, 4, 6, 8]


max(iterable) 최댓값 

max([1,2,3])
Out[93]: 3

max("python")
Out[94]: 'y'


min 최솟값

min([1,2,3])
Out[95]: 1

min("python")
Out[96]: 'h'

oct  정수 형태의 숫자를 8진수 문자열로 바꾸어 돌려주는 함수

oct(34)
Out[97]: '0o42'

oct(12345)
Out[98]: '0o30071'


open(filename,[mode]) 파일이름과 읽기 방법을 입력받아 파일 객체를 돌려주는 함수 
읽기 방법을 생략하면 기본값인 읽기전용모드(r) 파일 객체로 만들어 돌려준다

w : 쓰기 모드로 파일 열기
r : 읽기 모드로 파일 열기
a : 추가 모드로 파일 열기
b : 바이너리 모드로 파일 열기

b 는 w,r,a 와 함께 사용한다



ord(c) 문자의 아스키코드 값 반환

ord('a')
Out[108]: 97

ord('0')
Out[109]: 48


pow(a,b) a의 b제곱한 결과값 반환

pow(2,4)
Out[110]: 16

pow(3,3)
Out[111]: 27


range([start],stop,[step]) for문과 자주 사용되는 함수 
입력받은 숫자에 해당하는 범위 값을 반복 가능한 객체로 만들어 반환

list(range(5))
Out[112]: [0, 1, 2, 3, 4]

list(range(5,10))  (시작숫자, 끝숫자) -> 끝 숫자는 해당 범위에 포함 안됨
Out[113]: [5, 6, 7, 8, 9]

세번째 인수는 숫자 사이의 거리
(시작숫자,끝숫자, 숫자 사이의 거리)

list(range(1,10,2))
Out[114]: [1, 3, 5, 7, 9]

list(range(0,-10,-1))
Out[115]: [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]


round 반올림 (숫자,자릿수)


round(4,6)
Out[116]: 4

round(4,2)
Out[117]: 4

round(5.678,2)
Out[118]: 5.68


sorted(iterable) 입력값을 정렬한 후 결과를 리스트로 돌려주는 함수

sorted([3,1,2])
Out[119]: [1, 2, 3]

sorted(['a','c','b'])
Out[120]: ['a', 'b', 'c']

sorted("zero")
Out[121]: ['e', 'o', 'r', 'z']

sorted((3,2,1))
Out[122]: [1, 2, 3]


str(object) 문자열 형태를 객체로 변환

str(3)
Out[123]: '3'

str('hi')
Out[124]: 'hi'

str('hi'.upper())
Out[125]: 'HI'


sum(iterable) 입력받은 리스트나 튜플의 모든 요소의 합을 반환

sum([1,2,3])
Out[126]: 6

sum([4,5,6])
Out[127]: 15


tuple(iterable) 반복 가능한 자료형을 입력받아 튜플 형태로 바꿔 반환하는 함수
만약 튜플링 입력으로 들어오면 그대로 돌려줌

tuple('abc')
Out[128]: ('a', 'b', 'c')

tuple([1,2,3])
Out[129]: (1, 2, 3)

tuple((1,2,3))
Out[130]: (1, 2, 3)



type(object) 입력값의 자료형이 무엇인지 알려줌

type("abc")
Out[131]: str

type([])
Out[132]: list

type(open("test",'w'))
Out[133]: _io.TextIOWrapper



zip(*iterable) 동일한 개수로 이루어진 자료형을 묶어 주는 역할을 하는 함수

list(zip([1,2,3],[4,5,6]))
Out[134]: [(1, 4), (2, 5), (3, 6)]

list(zip([1,2,3],[4,5,6],[7,8,9]))
Out[135]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

list(zip("abc","def"))
Out[136]: [('a', 'd'), ('b', 'e'), ('c', 'f')]










 
 

result = 0

def add(num):
    global result
    result += num;
    return result

print(add(3))
print(add(4))

3
7



result1 = 0
result2 = 0

def add1(num):
    global result1
    result1 += num
    return result1

def add2(num):
    global result2
    result2 += num
    return result2

print(add1(3))
print(add1(4))
print(add2(3))
print(add2(7))

3
7
3
10


계산기 라는 클래스를 이용하여 메소드를 호출하는 예제 
class Calculator:
    def __init__(self):
        self.result = 0
        
    def add(self, num):
        self.result += num
        return self.result
        
    def minus(self, num):
        self.result -= num
        return self.result
    

cal1 = Calculator()
cal2 = Calculator()


print(cal1.add(3))
print(cal1.add(4))
print(cal2.add(3))
print(cal2.add(7))

print(cal1.minus(3))
print(cal1.minus(4))
print(cal2.minus(3))
print(cal2.minus(7))


3
7
3
10

4
0
7
0



class FourCal:
    def setdata(self,first,second):
        self.first = first
        self.second = second
        

a = FourCal()

a.setdata(4,2)

FourCal.setdata(a,4,2)

a = FourCal()

a.setdata(4,2)

print(a.first)
4

print(a.second)
2

a = FourCal()
b = FourCal()

a.setdata(4,2)

print(a.first)
4

b.setdata(3,7)

print(b.first)
3

 a = FourCal()

 b = FourCal()

 a.setdata(4,2)

 b.setdata(3,7)

id(a.first)
Out[22]: 140727042145440

id(b.first)
Out[23]: 140727042145408



class FourCal:
    def setdata(self,first,second):
        self.first = first
        self.second = second
    def add(self):
        result = self.first + self.second
        return result
    def minus(self):
        result = self.first - self.second
        return result
    def mul(self):
        result = self.first * self.second
        return result
    def div(self):
        result = self.first / self.second
        return result
    def mod(self):
        result = self.first % self.second
        return result
        

a = FourCal()

a.setdata(4,2)

print(a.add())
6

a = FourCal()

a.setdata(4,2)

print(a.minus())
2

print(a.mul())
8

print(a.div())
2.0

print(a.mod())
0

b = FourCal()

b.setdata(6,8)

print(b.add())
14

print(b.minus())
-2

print(b.mul())
48

print(b.div())
0.75

print(b.mod())
6


class FourCal:
    def __init__(self,first,second):
        self.first = first
        self.second = second
    def setdata(self,first,second):
        self.first = first
        self.second = second
    def add(self):
        result = self.first + self.second
        return result
    def minus(self):
        result = self.first - self.second
        return result
    def mul(self):
        result = self.first * self.second
        return result
    def div(self):
        result = self.first / self.second
        return result
    def mod(self):
        result = self.first % self.second
        return result
        
        
  __init__ 생성자로 인식되어 객체가 생성되는 시점에 자동으로 호출되는 차이가 있음
  
  a = FourCal()
Traceback (most recent call last):

  File "<ipython-input-46-5cfa1e393ba9>", line 1, in <module>
    a = FourCal()

TypeError: __init__() missing 2 required positional arguments: 'first' and 'second'

-> first 와 second 에 대한 매개변수 값이 지정되지 않아서 오류 발생함


a = FourCal(4,2)  -> 매개변수 값을 설정해줘야 함 

print(a.first)
4

print(a.second)
2

a.add()
Out[50]: 6

a.div()
Out[51]: 2.0

a.minus()
Out[52]: 2

a.mul()
Out[53]: 8

a.mod()
Out[54]: 0


class MoreFourCal(FourCal):
    pass
    

a = MoreFourCal(4,2)

class 클래스이름(상속할 클래스 이름)

a.add()
Out[57]: 6

a.mul()
Out[58]: 8

a.div()
Out[60]: 2.0

a.mod()
Out[61]: 0

a.minus()
Out[62]: 2


class MoreFourCal(FourCal):
    def power(self):
        result = self.first ** self.second
        return result
        

a = MoreFourCal(4,2)

a.power()
Out[65]: 16

a = MoreFourCal(4,0)

a.div()
Traceback (most recent call last):

  File "<ipython-input-67-656340726662>", line 1, in <module>
    a.div()

  File "<ipython-input-45-e275ce6b2c97>", line 18, in div
    result = self.first / self.second

ZeroDivisionError: division by zero



div 메서드를 동일한 이름으로 다시 작성하였다. 
부모클래스(상속한 클래스) 에 있는 메소드를 동일한 이름으로 다시 만드는 것을 
메소드 오버라이딩(Overriding) - 자바하고 똑같은 개념 재정의 라고도 한다 

class SafeFourCal(FourCal):
    def div(self):
        if self.second == 0:
            return 0
        else:
            return self.first / self.second
            

a = SafeFourCal(4,0)

a.div()
Out[70]: 0


클래스 변수 : 클래스로 만든 모든 객체에 공유된다 (공유 변수) 라고 한다.
메모리 값도 같다.

class Family:
    lastname = "정"
    

print(Family.lastname)
정

a = Family()

b = Family()

print(a.lastname)
정

print(b.lastname)
정

Family.lastname = "비"

print(a.lastname)
비

print(b.lastname)
비



클래스 변수 보다는 객체변수를 사용하는 비율이 훨씬 높다
클래스명.클래스변수 


id(Family.lastname)
Out[80]: 2636158971296

id(a.lastname)
Out[81]: 2636158971296

id(b.lastname)
Out[82]: 2636158971296



#mod1.py
def add(a,b):
    return a + b

def minus(a,b):
    return a - b

print(add(1,4))
print(minus(4,2))

if __name__ == "__main__":
    print(add(1,4))
    print(add(4,2))  


cmd 명령어로 경로 이동해서 결과 확인 하는 부분  
C:\Users\Ff>D:

D:\>\Python
'\Python'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.

D:\>cd D:\Python

D:\Python>dir
 D 드라이브의 볼륨: 새 볼륨
 볼륨 일련 번호: 2EDE-6F59

 D:\Python 디렉터리

2021-02-21  오후 07:30    <DIR>          .
2021-02-21  오후 07:30    <DIR>          ..
2021-02-19  오후 05:51                34 direct.txt
2021-02-18  오후 11:02               281 marks2.py
2021-02-18  오후 11:08               267 marks3.py
2021-02-18  오후 10:57               792 test01.py
2021-02-18  오후 10:59               350 test02.py
2021-02-19  오후 05:55             1,703 test03.py
2021-02-20  오후 09:09             1,053 test04.py
2021-02-21  오후 07:30               189 test05.py
2021-02-19  오후 05:47               342 새파일.txt
               9개 파일               5,011 바이트
               2개 디렉터리  1,855,190,507,520 바이트 남음

D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import mod1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'mod1'
>>>
>>>
>>> exit

D:\Python>test05
'test05'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.

D:\Python>dir
 D 드라이브의 볼륨: 새 볼륨
 볼륨 일련 번호: 2EDE-6F59

 D:\Python 디렉터리

2021-02-21  오후 07:30    <DIR>          .
2021-02-21  오후 07:30    <DIR>          ..
2021-02-19  오후 05:51                34 direct.txt
2021-02-18  오후 11:02               281 marks2.py
2021-02-18  오후 11:08               267 marks3.py
2021-02-18  오후 10:57               792 test01.py
2021-02-18  오후 10:59               350 test02.py
2021-02-19  오후 05:55             1,703 test03.py
2021-02-20  오후 09:09             1,053 test04.py
2021-02-21  오후 07:30               189 test05.py
2021-02-19  오후 05:47               342 새파일.txt
               9개 파일               5,011 바이트
               2개 디렉터리  1,855,190,503,424 바이트 남음

D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test05
>>> print(test05.add(3,4))
7
>>> print(test05.minus(3,4))
-1
>>> from test05 import add
>>> add(3,4)
7
>>> from test05 import add,sub


D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test05
>>> ^Z


D:\Python>python test05.py
5
2

D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test05
5
2


>>> import test05
>>> 아무런 값도 출력 안됨


#mod2.py
PI = 3.141592

class Math:
    def solv(self, r):
        return PI * (r ** 2)
    
    def add(a, b):
        return a + b
    
cmd 명령어창
D:\Python>python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test06
>>> print(test06.PI)
3.141592
>>> a = test06.Math()
>>> print(a.solv(2))
12.566368


Comments