K3Python2018 OOP-01
- 14. FOR
for [変数] in [リスト]:
# 実行するプログラム
リストの中身を順に実行していくもの!(Pythonでは)
他言語ではこれはforeachなどという名前であること
が多い
- 25. plusplus(10)で行われている計算
plusplus(10)
= plusplus(9) + 10
= plusplus(8) + 9 + 10
= plusplus(7) + 8 + 9 + 10
= plusplus(6) + 7 + 8 + 9 + 10
= plusplus(5) + 6 + 7 + 8 + 9 + 10
= plusplus(4) + 5 + 6 + 7 + 8 + 9 + 10
= plusplus(3) + 4 + 5 + 6 + 7 + 8 + 9 + 10
= plusplus(2) + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
= plusplus(1) + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
= 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
- 43. コードにしてみる
class Player:
def __init__(self, _hp, _atk, _def, _spd, _url): # 変数の初期設定
self.hp = _hp
self.atk = _atk
self.defe = _def
self.spd = _spd
self.url = _url
def damage(self, enemyAtk):
dmg = enemyAtk - self.defe
if dmg < 1:
dmg = 1
self.hp -= dmg
各変数の値を設定する
selfが頭についているものはクラス全体の変数
selfが頭についていない変数はその関数が終わったら死ぬ変数
最初の引数はクラス自体を表す
- 44. コードにしてみる
player1 = Player(100, 30, 20, 10, "pl1.jpg")
print(player1.hp) # HPの100を出力
player1.damage(50) # Atk=50で攻撃され30ダメージ
print(player1.hp) # HPの70を出力
player2 = Player(100, 80, 10, 5, "pl2.jpg")
player1.damage(player2.atk) # pl2からpl1に攻撃
# Atk=80で攻撃され60ダメージ
print(player1.hp) # HPの10を出力
- 48. 練習問題②-トランプの大枠を作る
# テスト用プログラム例
deck = Deck()
for c in deck.cards:
print("{} {}".format(c.suit,c.number))
while len(deck.cards) != 0:
card = deck.draw()
print("You draw:{} {}".format(card.suit,card.number))
# これで全カードが二度出力されれば良い
# 順番は同じでなくてもOK→Deckクラスのdraw関数に依存