More Related Content
Similar to pf-8. メソッド,クラス,コンストラクタ,継承 (14)
More from kunihikokaneko1 (20)
pf-8. メソッド,クラス,コンストラクタ,継承
- 4. Python のクラスとオブジェクト
• 次の2つのオブジェクトを生成する Python プロ
グラム
• このとき,次のクラスを使うことにする
4
クラス名 C
属性 qty,
weight,
name
x 5 170.51 'apple'
y 3 40.97 ‘orange'
qty weight name
x = C(5, 170.51, 'apple')
y = C(3, 40.97, 'orange')
Python プログラム
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
Python プログラム
- 11. 継承
クラス名 C
属性 qty, weight, name
11
class C(object):
def __init__(self, qty, weight,
name):
self.qty = qty
self.weight = weight
self.name = name
def total(self):
return self.qty * self.weight
class E(C):
def __init__(self, qty, weight, name, price):
super(E, self).__init__(qty, weight,
name)
self.price = price
def payment(self):
return self.qty * self.price
クラス名 E
属性 qty, weight, name, price
クラス E は,スーパークラスで
あるクラス C の属性を継承する.
- 12. まとめ
• class クラス定義
• __init__ コンストラクタ
• self クラス定義内での自オブジェクトへアク
セス
• vars オブジェクトの属性名と値
• super 親クラス(スーパークラス)
12
- 16. ④ コードセルを新規作成し,Python プログラムを入れる.結果を確認.
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
x = C(5, 170.51, 'apple')
print(vars(x))
y = C(3, 40.97, 'orange')
print(vars(y))
16
- 17. ⑤ コードセルを新規作成し,Python プログラムを入れる.結果を確認.
class C(object):
def __init__(self, qty, weight, name):
self.qty = qty
self.weight = weight
self.name = name
def total(self):
return self.qty * self.weight
class E(C):
def __init__(self, qty, weight, name, price):
super().__init__(qty, weight, name)
self.price = price
def payment(self):
return self.qty * self.price
x2 = E(2, 875.34, 'melon', 500)
vars(x2)
print(x2.total())
print(x2.payment())
type(x2) 17
- 18. Python 関連ページ
• Python まとめページ
https://www.kkaneko.jp/tools/man/python.html
• Python プログラミングの基本
Python Tutor, VisuAlgo, Code Combat を使用
https://www.kkaneko.jp/pro/po/index.html
• Python プログラム例
https://www.kkaneko.jp/pro/python/index.html
• 人工知能の実行(Google Colaboratory を使用)
https://www.kkaneko.jp/ai/ni/index.html
• 人工知能の実行(Python を使用)(Windows 上)
https://www.kkaneko.jp/ai/deepim/index.html 18