練習問題 解答
3.6 練習問題 解答
問1
① ○
② ×:コンストラクタの名前は「__init__」、戻り値は「設定できない」制約がある。
③ ×:コンストラクタには第一引数を指定する必要があるが、引数名はselfでなくてもよい。
④ ○
⑤ ○
問2
① 戻り値の型が定義されている。
② コンストラクタのメソッド(__init__)に引数(self,person)が指定されいない。
③ コンストラクタのPesonPrintのメソッドに第一引数(self)が設定されていない。
#クラスPersonを定義
class Person:
#コンストラクタの定義
def __init__(self,person):
#戻り値の設定
self.person = person
def PersonPrint(self):
print(self.person)
Person1 = Person("田中")
Person1.PersonPrint()
問3
#クラスPersonを定義
class TestScore:
#コンストラクタの定義
def __init__(self,name,mathSc,scienceSc,english):
#名前
self.name = name
#数学の得点
self.mathSc = mathSc
#理科の得点
self.scienceSc = scienceSc
#英語の得点
self.english = english
#合計得点の計算
def culc_test(self):
#各得点をまとめたリスト
test_list = [self.mathSc,self.scienceSc,self.english ]
#合計得点を格納する変数totalの宣言
total = 0
#totalに合計得点を格納するためのfor文開始
for i in test_list:
total = total + i
print(self.name,'さんの数学の点数は',self.mathSc,'点です。')
print(self.name,'さんの理科の点数は', self.scienceSc,'点です。')
print(self.name,'さんの英語の点数は', self.english,'点です。')
print(self.name,'さんの合計得点は',total,'点です。')
#インスタンスの生成
person_1 = TestScore('田中',42,32,22)
#メソッドculc_testの呼び出し
person_1.culc_test()