Study Web Development

3월 22일

이전으로

Python

5. 함수

내장 함수

  1. 새 파일 s10_function10.py 생성
# str(): 인자를 문자열로 변환
print(str(3)) # '3'
print(type(str(3)))
print('-'*3)

# list(): 리스트 생성
print(list('abc')) # 문자열을 리스트로 변환
print(list((1,2,3))) # 튜플을 리스트로 변환
print('-'*3)

# tuple(): 튜플 생성
print(tuple('abc')) # 문자열을 튜플로 변환
print(tuple([1,2,3])) # 리스트를 튜플로 변환

모듈

  1. 새 PyDev Project ch05-module 생성하고 새 파일 s01_module.py 생성
# 모듈을 생성하고 불러오기
import hello

hello.greet1('도로롱')
hello.greet2('도로롱')
  1. 새 파일 hello.py 생성
def greet1(name):
    print(name + '님 안녕하세요!')

def greet2(name):
    print(name + '님 반갑습니다.')
math
  1. 새 파일 s02_module2.py 생성
import math

# 올림
print('math.ceil(12.3): ',math.ceil(12.3))
print('-'*3)

# 버림
print('math.floor(12.7): ',math.floor(12.7))
print('-'*3)

# round()는 math 모듈이 아니라 파이썬 내장 함수
print('round(15.679): ',round(15.679))
print('round(15.679): ',round(15.679,2))
print('-'*3)

# 합계 데이터를 실수형으로 반환
print(math.fsum([1,2,3,4,5]))
print('-'*3)
time, datetime
포맷 기호 의미 비고
%Y 네 자리 연도
%y 두 자리 연도
%m
%d
%A 요일 Sunday
%a 간략 요일 Sun
%H 24시 0~23
%I 12시 1~12
%p AM 또는 PM
%M
%S
  1. 새 파일 s03_module3.py 생성
import time

seconds = time.time() # 1970년 1월 1일 자정 이후 경과한 시간을 초 단위로 반환
print(seconds)
print('-'*3)

tm = time.localtime(seconds) # 현지 시간(Local Time)
print('년: ',tm.tm_year)
print('월: ',tm.tm_mon)
print('일: ',tm.tm_mday)
print('시: ',tm.tm_hour)
print('분: ',tm.tm_min)
print('초: ',tm.tm_sec)

# epoch time을 문자열로 변환
string = time.ctime(seconds)
print(string)
print('-'*3)

string2 = time.strftime('%Y년 %m월 %d일 %I:%M:%S %p',tm)
print(string2)
  1. 새 파일 s04_module4.py 생성
# 현재의 날짜와 시간 구하기
# datetime 모듈의 datetime 객체를 불러오기
from datetime import datetime

today = datetime.now()
print('%s년' % today.year)
print('%s월' % today.month)
print('%s일' % today.day)
print('%s시' % today.hour)
print('%s분' % today.minute)
print('%s초' % today.second)

string = today.strftime('%Y/%m/%d %H:%M:%S')
print(string)
random
  1. 새 파일 s05_module5.py 생성
import random

print('random.random(): ',random.random()) # 0부터 1 전까지의 랜덤 수
print('random.random(): ',random.random())
print('-'*3)

print('random.uniform(1,10): ',random.uniform(1,10)) # 1부터 10 직전까지의 랜덤 수
print('random.uniform(1,10): ',random.uniform(1,10))
print('-'*3)

print('random.randint(1,6): ',random.randint(1,6)) # 1부터 6까지의 랜덤 수
print('random.randint(1,6): ',random.randint(1,6))
print('-'*3)

print('random.choice([1,2,3,4,5,6]): ',random.choice([1,2,3,4,5,6]))
print('random.choice("python"): ',random.choice('python'))
print('-'*3)

list1 = [15,23,4,88,7]
print('원래의 리스트: ',list1)
random.shuffle(list1) # list1의 순서를 섞음
print('순서가 변경된 리스트:',list1)
print('-'*3)

6. 클래스

  1. 새 PyDev Project ch06-class 생성하고 새 파일 s01_class.py 생성
# 클래스 정의
class Service: # Java와 달리 접근 제한자가 없음
    name = '도로롱' # 클래스 변수

# 객체 생성
test = Service()
print(test)
print('-'*3)

print(test.name) # .으로 하위 요소 접근
print('-'*3)

test.name = 'sleepy' # 값 변경
print(test.name)
  1. 새 파일 s02_class2.py 생성
# 클래스 정의
class Person:
    name = 'Default Name'

# 객체 생성
p1 = Person()
p2 = Person()

print('p1.name: ',p1.name)
print('p2.name: ',p2.name)
print('-'*3)

p1.name = '도로롱' # 객체가 생성되면 변수 값은 객체 단위로 관리됨
print('p1.name: ',p1.name)
print('p2.name: ',p2.name)
print('-'*3)

p2.name = 'sleepy'
print('p1.name: ',p1.name)
print('p2.name: ',p2.name)
print('-'*3)

self

  1. 새 파일 s03_class3.py 생성
# 클래스 정의
class Person:
    name = 'Default Name' # 클래스 변수
    def printName(self): # 메서드
        print('My Name is {0}'.format(self.name)) # name은 지역 변수 또는 전역 변수를 의미하며, 객체 자신의 변수 name은 self를 통해 접근해야 함

# 객체 생성
p = Person()

print(p.name)
p.printName()
print('-'*3)

p.name = '도로롱'
p.printName()
  1. 새 파일 s04_class4.py 생성
# 클래스 정의
class Service:
    def sum(self,a,b): # 메서드 정의시 첫 번째 인자는 반드시 self여야 함
        result = a + b # result와 인자는 지역 변수
        print('%s + %s = %s입니다' % (a,b,result)) # 실수, 정수 구분하지 않고 %s로 처리 가능

# 객체 생성
s = Service()
s.sum(1,2)
print('-'*3)

# 클래스 정의
class Lunch:
    name = '도로롱'
    def eat(self,food):
        print('%s님이 %s을(를) 먹습니다' % (self.name,food))

# 객체 생성
a = Lunch()
a.eat('샌드위치')
print('-'*3)
  1. 새 파일 s05_class5.py 생성
# 전역 변수
from pip._vendor.typing_extensions import Self
str = 'NOT Class Member'

# 클래스 정의
class GString:
    str = '' # 클래스 변수
    def setStr(self,msg):
        self.str = msg # 클래스 변수의 값을 변경
    def print(self):
        print(self.str) # 클래스 변수를 출력
        print(str) # 전역 변수를 출력

# 객체 생성
g = GString()
g.setStr('First Message')
g.print()

__init__

  1. 새 파일 s06_class6.py 생성
# 클래스 정의
class Service:
    def __init__(self,name):
        self.name = name
    def sum(self,a,b):
        result = a + b
        print('%s님 %s + %s = %s입니다' % (self.name,a,b,result))

# 객체 생성
s = Service('도로롱')

# 객체의 메서드 호출
s.sum(1,2)
print('-'*3)

s.name = 'sleepy'
s.sum(10,20)
  1. 새 파일 s07_class7.py 생성
# 클래스 정의
class Account:
    # 생성자
    def __init__(self,balance):
        self.balance = balance
    # 메서드
    def deposit(self,money):
        self.balance += money
        if money>0:
            print('{0:,}원을 예금하였습니다'.format(money))
        elif money<0:
            print('{0:,}원을 출금하였습니다'.format(abs(money)))
    def inquire(self):
        print('잔액: {0:,}원입니다'.format(self.balance)) # {0:,}는 세 자리씩 ,로 끊어 표현

# 객체 생성
a = Account(8000)
a.inquire()
a.deposit(-3000)
a.inquire()
print('-'*3)

b = Account(12000)
b.inquire()

__del__

  1. 새 파일 s08_class8.py 생성
# 클래스 정의
class MyClass:
    # 생성자
    def __init__(self,value):
        self.vale = value
        print('Class is created! Value = ', value)
    # 메서드
    def play(self):
        print('play 메서드')
    # 소멸자
    def __del__(self):
        print('Class is deleted!')

# 객체 생성
a = MyClass(100)
a.play()
a.play()

클래스 상속

  1. 새 파일 s09_class9.py 생성
# 상속: 기존 클래스를 확장하여 멤버를 추가하거나 동작을 변경하는 방법
class Human:
    # 생성자
    def __init__(self,age,name):
        self.age = age
        self.name = name
    # 메서드
    def intro(self):
        print(str(self.age) + '세, ' + self.name + '입니다')

class Student(Human): # 클래스 정의시 인자로 전달한 클래스를 상속받음
    def __init__(self,age,name,num):
        super().__init__(age, name)
        self.num = num
    def intro(self): # 메서드 재정의
        super().intro()
        print('학번: ' + str(self.num))
    def study(self):
        print('오늘은 수요일')

a = Human(20,'도로롱')
a.intro()
print('-'*3)

b = Student(22, '도로롱', 1234)
b.intro()
b.study()

다음으로