Today I Learned

[TIL] 파이썬 기초 수업 끝 -

by Holly Yoon

TIL

1. 클래스 연습 - 스타크래프트 예제

  • 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

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는.. 주말 동안 정리해서 업데이트 할 예정..
  • 폭풍같은 일주일이었다

블로그의 정보

Study Log by Holly

Holly Yoon

활동하기