[TIL] 파이썬 기초 수업 끝 -
by Holly Yoon1. 클래스 연습 - 스타크래프트 예제
- Marine : health(40), attack_pow(5), attack(상대체력감소)
- Medic : health(60), heal_pow(6), heal(상대체력회복)
- Marine과 Medic Class를 각각 정의해주세요.
- attach(), heal() 은 각각 target변수를 넣으면 상대방의 체력이 증가/감소 하도록 만들어주세요.
- 체력의 경계를 정해주세요. (0~max_health)
class Marine:
def __init__(self, health=40, attack_pow=5):
self.health = self.max_health = health
self.attack_pow = attack_pow
def attack(self, target):
target.health -= self.attack_pow
if target.health <0:
target.health=0
class Medic:
def __init__(self, health=60, heal_pow=6):
self.health = self.max_health = health
self.heal_pow = heal_pow
def heal(self, target):
target.health += self.heal_pow
if target.health > target.max_health:
target.health = target.max_health
marine = Marine()
medic = Medic()
marine.attack(medic)
medic.health
>>50
2. get/set
- 파이썬스러운 코딩은 아니나 객체지향 언어의 특성을 파이썬에서 활용할 수 있다.
class Stock():
def __init__(self):
self.price=None
def setPrice(self, price): #set은 데이터 넣어주기
if price>10000:
self.__price=price
else:
self.__price=5000
def getPrice(self): #get은 데이터 꺼내오기
return self.__price
stock=Stock()
stock.setPrice(3000)
print('주문 넣는다. 가격 : %s'%stock.getPrice())
- set, get을 함수 안에 넣어줌으로써, 변수 조건을 주고 받을 수 있게 된다.
class Stock():
def __init__(self):
self.price=None
def setPrice(self, price):
if price>10000:
self.__price=price
else:
self.__price=5000
def getPrice(self):
assert self.__price !=None, "가격이 None이네요!"
return self.__price
- assert으로 에러메시지를 발생시켜줄 수 있다.
- 요 부분은 유튜브 <프로그램 동산, 파이썬 정석 13강> 참고
3. get/set - 활용
class Person:
def __init__(self, pw):
self.hidden_pw = pw
@property
def pw(self):
return self.hidden_pw[:2] + '****'
@pw.setter #위에 pw()함수와 연결되어있음을 표시해준다
def pw(self, new_pw):
input_pw = input('insert password : ')
if input_pw == self.hidden_pw:
self.hidden_pw = new_pw
else:
print('wrong password!')
- abcd로 비밀번호를 지정해준다.
person = Person('abcd')
- person.pw 에 'qwer'를 넣어 new_pw를 만들고 기존 hidden_pw를 업데이트 하자.
person.pw
>>'qw****'
person.pw='qwer'
>>insert passsword: 1
wrong password!
>>insert password: abcd
#qwer로 passwrod가 재정의 된다
***
- 모듈/패키지/is a has a는.. 주말 동안 정리해서 업데이트 할 예정..
- 폭풍같은 일주일이었다
'TIL' 카테고리의 다른 글
[TIL] 스크랩핑 with Pandas (0) | 2023.01.12 |
---|---|
[TIL] Pandas 시작하기 (0) | 2023.01.10 |
[TIL] 파이썬 기초 - 클래스, 상속, 상관분석 (0) | 2023.01.05 |
[TIL] 파이썬 기초 (함수/파파고 API) (0) | 2023.01.04 |
[TIL] 파이썬 기초 (반복문, 조건문, 조건부확률) (0) | 2023.01.03 |
블로그의 정보
Study Log by Holly
Holly Yoon