K3Python2018 OOP-02
- 9. 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
- 16. コードにしてみる
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が頭についていない変数はその関数が終わったら死ぬ変数
最初の引数はクラス自体を表す
- 17. コードにしてみる
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を出力
- 19. 復習問題(再帰) ― 標準入力の扱い
a = input() # これが標準入力
st = a.split()
# スペース区切りで入力されたものをsplit()をつけると、リストにして
くれる
# st[0] = "10", st[1] = "50", st[2] = "20" みたいになる
a1 = int(st[0]) # これで最初の文字列10を数値の10に変えられる
- 20. 復習問題(再帰) ― 大まかな流れ
def nisebonacchi(a1,a2,n):
# 再帰プログラムを書く
print ----
s = input() # 単に入力を待つならこう
# 文字を処理してa1,a2,nを数値として取り出す
print(nisebonacchi(a1,a2,n))
- 26. 保守性とカプセル化
class Person:
def __init__(self, h, w):
self.__height = 100
self.__weight = 0
self.set_height(h)
self.set_weight(w)
def get_height(self):
return __height
def get_weight(self):
return __weight
def set_height(self, h):
if 100 <= h < 300:
self.__height = h
else:
print("Error: …")
def set_weight(self, w):
if 0 <= w < 300:
self.__weight = w
else:
print("Error: …")
- 30. 練習問題のイメージ
class ComplexNumber:
def __init__(self, r, i):
# 初期値設定
def addition(self, comp):
# 足し合わせる
return ComplexNumber(r, i)
def subtraction(self, comp):
# 引く
return ComplexNumber(r, i)
def multiplication(self, comp):
# 掛ける
return ComplexNumber(r,i)
def to_string(self):
# __str__の仕様が分かる人はそれでもOK
return ----
c1 = ComplexNumber(5,2)
c2 = ComplexNumber(-4,2)
print(c1.to_string())
print(c2.to_string())
pl = c1.addition(c2)
mi = c1.subtraction(c2)
mul = c1.multiplication(c2)
print(pl.to_string())
print(mi.to_string())
print(mul.to_string())