https://www.inflearn.com/course/%EB%82%98%EB%8F%84%EC%BD%94%EB%94%A9-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EA%B8%B0%EB%B3%B8
[지금 무료] 파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자 | 나도코딩 - 인프런
나도코딩 | 6시간. 여러분이 파이썬 개발자가 되는데 필요한 시간입니다. 핵심 내용만 선정 / 챕터마다 퀴즈 & 해설 / 실생활 기반 예제로 아주 쉽게 설명합니다. 그리고 완전 무료입니다., 배우지
www.inflearn.com
강의명 : 파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자
수강 기한 : 무제한
강의 구성 : 71강
시작일 : 2024.6.3.
커리큘럼 :
[기본편]
1. 기본문법
1) 자료형 (6/3 학습)
2) 연산자 (6/3 학습)
3) 문자열처리 (6/3 학습)
4) 자료구조 (6/3 학습)
5) 제어문 (6/4 학습)
6) 함수 (6/4 학습)
7) 입출력 (6/4 학습)
8) 클래스 (6/5 학습)
9) 예외처리 (6/5 학습)
10) 모듈과 패키지 (6/5 학습)
2. 실생활 기반 예제
3. 퀴즈
8) 클래스 ㄱㅂㅈㄱ
name = "마린"
hp = 40
damage = 5
print("{0}유닛이 생성되었습니다".format(name))
print("체력 {0}, 공격력 {1}\n".format(hp, damage))
name = "마린2"
hp = 40
damage = 5
print("{0}유닛이 생성되었습니다".format(name))
print("체력 {0}, 공격력 {1}\n".format(hp, damage))
class unit:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
print("{0}유닛이 생성되었습니다".format(self.name))
print("체력 {0}, 공격력 {1}\n".format(self.hp, self.damage))
marine1 = unit("마린", 40, 5)
marine2 = unit("마린", 40, 5)
tank = unit("탱크", 140, 35)
class를 이용해서 서로 다른 유닛을 만들어냇따
__init__ : 파이썬에서 쓰이는 생성자? 마린이나 탱크같은 "객체"가 만들어질때 자동으로 호출되는 부분?
객체 : 클래스로부터 만들어지는 것들을 객체라고 부른다아 : Object (unit이라는 class에 이름, hp, 데미지 값을 넣어서 만들어진 것)
이때 마린과 탱크는 유닛 클래스의 인스턴스라고 한다고? : Instance
init함수에 정의된 변수 (self)뺀 갯수만큼 값을 넣어줘야함
***찾아보니까 init은 파이썬에서만 사용하는 함수이고 initialize 즉 초기화, 기본값 설정을 의미
self 는 클래스 그 자체 스스로를 지칭하는 변수명으로 self외에 다른 어떤 문자열이 들어가도 상관없다
https://writingstudio.tistory.com/entry/%ED%8C%8C%EC%9D%B4%EC%8D%ACPython-%ED%81%B4%EB%9E%98%EC%8A%A4class-%EC%95%88-def-initself-%EC%99%80-self-%EB%93%B1%EC%9D%84-%EC%A0%9C%EB%8C%80%EB%A1%9C-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0
파이썬(Python): 클래스(class) 안 def __init__(self): 와 self 등을 제대로 이해하기
"def __init__(self):" 파이썬python을 약간이라도 다루기 시작한 사람이라면 이내 마주치는 구문이다. 개인적으로는 def __init__(self) 구문은 파이썬에서만 사용하는 함수로 안다. 다른 언어에서 본 적이
writingstudio.tistory.com
어..어렵따...
멤버변수 : class내에서 정의된 변수
.name
.hp
.damage
wraith1 = unit("레이스", 80, 5)
print("유닛이름 : {0}, 공격력:{1}".format(wraith1.name, wraith1.damage))
wraith2 = unit("빼앗은 레이스", 80, 5)
wraith2.clocking = True
if wraith2.clocking == True:
print("{0}은 현재 클로킹 상태입니다.".format(wraith2.name))
if wraith1.clocking == True:
print("{0}은 현재 클로킹 상태입니다.".format(wraith1.name)) # 오류 발생
.clocking 이라는 변수를 class 밖에서 확장할 수 있다.
다만 지정해준 객체에서만 사용 가능하고 다른 객체에서는 인정되지 않는다.
스타크래프트 강의같기도..? 쌤.. 마인드컨트롤 몰라도되는거아니냐고용.ㅋ
#공격 유닛
class AttackUnit:
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
def attack(self, location): #메소드
print("{0}: {1} 방향으로 적군을 공격합니다. [공격력 : {2}]".format(self.name, location, self.damage))
def damaged(self, damage):
print("{0}: {1} 데미지를 입었습니다.".format(self.name, damage))
self.hp -= damage
print("{0}: 현재 체력은 {1}입니다.".format(self.name, self.hp))
if self.hp <= 0 :
print("{0}: 파괴되었습니다.".format(self.name))
firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("4시")
firebat1.damaged(25)
firebat1.damaged(25)
class 안에 정의된 attack, damaged 는 메소드 라고 한다
self.xxx => 유닛 생성시 정의해준 값을 받는다
그 외에는 메소드 호출?시 넣어준 값을 받는다
#일반유닛
class unit:
def __init__(self, name, hp):
self.name = name
self.hp = hp
#공격 유닛
class AttackUnit(unit):
def __init__(self, name, hp, damage):
unit.__init__(self, name, hp)
self.damage = damage
class 내용이 중복되는 경우 상속을 통해 고대로 쓸수있다
class 클래스명(상속받을 클래스명): # 자식(부모)
def __init__(self, a, b, c): #그대로 써주고
unit.__init__(self, a, b) #상속받는 내용 가져오고
self.c = c #추가되는 메소드 써주기
#공중 유닛 : 공격x
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0}: {1}방향으로 날아갑니다. [속도:{2}]".format(name, location, self.flying_speed))
#공중 공격 유닛
class FlyableAttackUnit(Flyable, AttackUnit):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, flying_speed)
Flyable.__init__(self, flying_speed)
#발키리:공중공격유닛
valkyrie = FlyableAttackUnit("발키리",40, 5, 3)
valkyrie.fly(valkyrie.name, "3시") #flyableAttackUnit에 name 정의 안해놔서 valkyrie.name으로 넣어줌
valkyrie.attack("3시")
valkyrie.damaged(30)
다중상속을 받아서 여러개 메소드를 받아올 수 있다. 그치 맞지.. flyable의 fly라는메소드를 가져와서 썼음
다른것들도 써봤다 잘 실행됨
메소드 오버라이딩......
부모클래스를 상속받은 자식클래스에서 메소드 재정의하여 사용
#일반유닛
class unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location):
print("[지상유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]".format(self.name, location, self.speed))
#공중 공격 유닛
class FlyableAttackUnit(Flyable, AttackUnit): #attackunit이 unit을 상속함으로 같이 수정해줘야함
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, flying_speed) #speed 0 처리
Flyable.__init__(self, flying_speed)
def move(self, location):
print("[공중유닛 이동]")
self.fly(self.name, location)
FAU에다가 move를 재정의
flyable을 상속한 클래스이므로 self.fly 를 받아온다
#벌쳐 :지상, 빠름
vulture = AttackUnit("벌쳐", 80, 10, 20)
#배틀크루져
battlecruiser = FlyableAttackUnit("배틀크루져", 500, 25, 3)
vulture.move("11시")
# battlecruiser.fly(battlecruiser.name, "9시") #매번 지상/공중 유닛에 따라 다른 함수를 써주는게 불필요함
battlecruiser.move("9시")
각각 유닛의 클래스에 따라 move 함수를 각기 다르게 받아옴
#건물 유닛
class buildingUnit(unit):
def __init__(self, name, hp, location):
pass
#pass
supply_depot = buildingUnit("서플라이 디폿", 500, "3시")
def game_start():
print("[알림] 새로운 게임을 시작합니다.")
def game_over():
pass
game_start()
game_over()
#건물 유닛
class buildingUnit(unit):
def __init__(self, name, hp, location):
#unit.__init__(self, name, hp, 0)
super().__init__(name, hp, 0) #self 빼고 init > 부모 상속값 초기화
self.location = location
super().__init__ > 다중 상속에는 적용 불가
#부동산 퀴즈 ~
#총 3대의 매물이 있습니다.
#강남 아파트 매매 10억 2010년
#마포 오피스텔 전세 5월 2007년
#송파 빌라 월세 500/50 2000년
class House:
def __init__(self, location, house_type, deal_type, price, completion_year):
self.location = location
self.house_type= house_type
self.dear_type= deal_type
self.price= price
self.completion_year= completion_year
def show_detail(self):
print(self.location, self.house_type, self.dear_type, self.price, self.completion_year)
house = []
house1 = House("강남", "아파트", "매매", "10억", "2010년") #클래스 이용해서 아이템 만들어주기
house2= House("마포", "오피스텔", "전세", "5억", "2007년")
house3 = House("송파", "빌라", "월세", "500/50", "2000년")
house.append(house1)
house.append(house2)
house.append(house3)
print("총 {0}개의 매물이 있습니다.".format(len(house))) #리스트 길이 = 아이템? 개수
for matter in house:
matter.show_detail()
왜 막상 내가 하려고하면 뭐부터 해야할지 모르겠는걸까?
class 강의는 나중에 꼭 다시 복습해보자
9) 예외처리
try:
print("나누기 전용 계산기 입니다.")
num1 = int(input("숫자를 입력하세요.:"))
num2 = int(input("숫자를 입력하세요.:"))
print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
print("오류우! 숫자만 입력하세요")
except ZeroDivisionError:
print("오류우! 0으로 나눌수 없습니다.")
# except ZeroDivisionError as err :
# print(err)
try:
print("나누기 전용 계산기 입니다.")
nums = [] #리스트를 만들고
nums.append(int(input("숫자를 입력하세요.:")))
nums.append(int(input("숫자를 입력하세요.")))
# nums.append(int(nums[0]/nums[1]))
print("{0} / {1} = {2}".format(nums[0], nums[1], nums[2]))
except ValueError:
print("오류우! 숫자만 입력하세요")
except ZeroDivisionError:
print("오류우! 0으로 나눌수 없습니다.")
# except ZeroDivisionError as err :
# print(err)
except Exception as err:
print("알 수 없는 에러가 발생했습니다.")
print(err)
위에서 정해준 ValueError, ZeroDivisionError 2가지 오류 외에 나머지 유형은 마지막줄 except: 로 처리 가능
try:
print("한자리수 전용 계산기 입니다.")
num1 = int(input("숫자를 입력하세요 : "))
num2 = int(input("숫자를 입력하세요 : "))
num3 = int(num1/num2)
print("{0} / {1} = {2}".format(num1, num2, num3))
if num1 >=10 or num2 >= 10:
raise ValueError
except ValueError :
print("오류! 한자리 숫자만 입력하세요")
지정된 조건 외 값은 에러 발생시킬 수 있다
class BignumberError(Exception):
pass
try:
print("한자리수 전용 계산기 입니다.")
num1 = int(input("숫자를 입력하세요 : "))
num2 = int(input("숫자를 입력하세요 : "))
num3 = int(num1/num2)
print("{0} / {1} = {2}".format(num1, num2, num3))
if num1 >=10 or num2 >= 10:
raise BignumberError
except ValueError :
print("오류! 한자리 숫자만 입력하세요")
except BignumberError :
print("비꾸넘버에러 발생!")
class를 이용해서 내가 지정한 에러명을 사용할수있다. - Exception class를 상속받음
class BignumberError(Exception):
def __init__(self, msg):
self.msg = msg
try:
print("한자리수 전용 계산기 입니다.")
num1 = int(input("숫자를 입력하세요 : "))
num2 = int(input("숫자를 입력하세요 : "))
num3 = int(num1/num2)
print("{0} / {1} = {2}".format(num1, num2, num3))
if num1 >=10 or num2 >= 10:
raise BignumberError("입력값 :{0}, {1}".format(num1, num2))
except ValueError :
print("오류! 한자리 숫자만 입력하세요")
except BignumberError as err :
print("비꾸넘버에러 발생!")
print(err)
BignumberError 기본값 설정. msg 인자를 추가 -> BignumberError는 msg를 인자로 하는 함수가 된다?
에러 발생 설정해줄때 msg를 입력해준다. -> err로 출력하게됨 음...
finally:
print("계산기를 이용해주셔서 감사합니다.")
정상/에러처리 시 에 무조건 출력되는 문구 작성
#치킨 주문 퀴즈!
class SoldOutError(Exception):
def __init__(self):
pass
try:
chicken = 10
waiting = 1
while(True):
print("[남은 치킨은 {0}마리 입니다.]".format(chicken))
order = int(input("몇 마리 주문하시겠습니까? :"))
if order <= 0 :
raise ValueError
if order > chicken :
print("죄송합니다. 재료가 부족합니다.")
else :
print("주문번호 {0}번 손님, {1}마리 주문 완료되었습니다.".format(waiting, order))
waiting += 1
chicken -= order
if chicken <= 0 :
raise SoldOutError
except ValueError:
print("잘못된 값을 입력하였습니다.")
except SoldOutError:
print("재고가 소진되어 더이상 주문을 받지 않습니다.")
break
헤헷 ^ _^
if 밑에 elif 로 주문양<=0이면~으로 조건문 걸어주는게 좀더 예쁜? 코드같다
while문 안에서 try를 해줘야하는듯 & 프래그램 종료를 위해 soldout 시 break 써줘야함
10) 모듈
theater_module.py
def price(people):
print("{0}명 일반 티켓 가격은 {1}원 입니다.".format(people, people * 10000))
def price_morning(people):
print("{0}명 조조 티켓 가격은 {1}원 입니다.".format(people, people * 6000))
def price_soldier(people):
print("{0}명 군인 티켓 가격은 {1}원 입니다.".format(people, people * 4000))
import theater_module
theater_module.price(3)
theater_module.price_morning(3)
theater_module.price_soldier(3)
저.. 강의랑 똑같이 적었는데 왜 AttributeError가 뜰까요?? ? ? / 미취겟네
price가 왜 업다는거여 .......................... > 모듈.py 파일을 저장을 안하고 불러와서 그런거였땅..부들부들
여러가지 방법..
import theater_module
theater_module.price(3)
theater_module.price_morning(3)
theater_module.price_soldier(3)
import theater_module as mv
mv.price(3)
from theater_module import *
price(3)
price_morning(4)
price_soldier(5)
from theater_module import price, price_morning
price(3)
price_morning(4)
# price_soldier(5)
from theater_module import price_soldier as price
price(3)
패키지 = 모듈의 집합 (한 폴더에 모듈 여러개를 넣어놓고 호출해서 사용)
import travel.thailand #import 폴더명.파일명 >> 클래스나 함수 import 불가
trip_to = travel.thailand.ThailandPackage() #변수 = 폴더.파일.클래스 객체
trip_to.detail() #함수 호출
from travel.thailand import ThailandPackage #from import 로는 class 가능
trip_to = ThailandPackage() #바로 class 사용
trip_to.detail()
import travel.vietnam
trip_to = travel.vietnam.VietnamPackage()
trip_to.detail()
trip_to 라는 변수를 thailandpackage 클래스로 생성해주고
그 객체를 통해 detail 함수 호출 ?
from travel import * #>> 패키지(모듈)안에서 공개 범위를 설정해줘야함
trip_to = vietnam.VietnamPackage()
trip_to = thailand.ThailandPackage()
trip_to.detail()
__init__.py 에서 아래와 같이 설정
__all__ = ["vietnam", "thailand"]
if __name__ == "__main__":
print("Thailand 모듈을 직접 실행하였음")
trip_to = ThailandPackage()
trip_to.detail()
else :
print("Thailand 외부에서 모듈 호출")
모듈 호출 위치에 따라 다른 문구 프린트 가능 (?)
import inspect
import random
print(inspect.getfile(random))
print(inspect.getfile(thailand))
inspect 를 import로 가지고와서 파일 위치를 출력
pipy > site 참조
내장함수 : improt 없이 바로 쓸수 있는 함수 ex. input, dir ....
https://docs.python.org/3/library/functions.html
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...
docs.python.org
외장함수
https://docs.python.org/3/py-modindex.html
Python Module Index — Python 3.12.3 documentation
numbers Numeric abstract base classes (Complex, Real, Integral, etc.).
docs.python.org
import glob
print(glob.glob(".py")) #경로 내 폴더/파일 목록 조회
import os
print(os.getcwd()) # 현재 디렉토리 조회
folder = "sample_dir"
if os.path.exists(folder):
print("이미 존재하는 폴더입니다.")
os.rmdir(folder) #remove
print(folder, "폴더를 삭제했습니다.")
else:
os.makedirs(folder) # sample_dir 라는 폴더 생성
print(folder, "폴더를 생성하였습니다.")
import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S"))
import datetime
print("오늘 날짜는 ", datetime.date.today())
today = datetime.date.today()
td = datetime.timedelta(days=100)
print("우리가 만난지 100일은", today + td)
시그니쳐 모듈 만들기로 수업 끝 !