練習問題 解答

3.6 練習問題 解答

問1

① ○
② ×:コンストラクタの名前は「__init__」、戻り値は「設定できない」制約がある。
③ ×:コンストラクタには第一引数を指定する必要があるが、引数名はselfでなくてもよい。
④ ○
⑤ ○

問2

① 戻り値の型が定義されている。
② コンストラクタのメソッド(__init__)に引数(self,person)が指定されいない。
③ コンストラクタのPesonPrintのメソッドに第一引数(self)が設定されていない。

1#クラスPersonを定義
2class Person:
3    #コンストラクタの定義
4    def __init__(self,person):
5        #戻り値の設定
6        self.person = person
7    def PersonPrint(self):
8        print(self.person)
9 
10Person1 = Person("田中")
11Person1.PersonPrint()

問3

1#クラスPersonを定義
2class TestScore:
3    #コンストラクタの定義
4    def __init__(self,name,mathSc,scienceSc,english):
5        #名前
6        self.name = name
7        #数学の得点
8        self.mathSc = mathSc
9        #理科の得点
10        self.scienceSc = scienceSc
11        #英語の得点
12        self.english = english
13 
14    #合計得点の計算
15    def culc_test(self):
16        #各得点をまとめたリスト
17        test_list = [self.mathSc,self.scienceSc,self.english ]
18 
19        #合計得点を格納する変数totalの宣言
20        total = 0
21 
22        #totalに合計得点を格納するためのfor文開始
23        for i in test_list:
24            total = total + i
25        print(self.name,'さんの数学の点数は',self.mathSc,'点です。')
26        print(self.name,'さんの理科の点数は', self.scienceSc,'点です。')
27        print(self.name,'さんの英語の点数は', self.english,'点です。')
28        print(self.name,'さんの合計得点は',total,'点です。')
29 
30#インスタンスの生成
31person_1 = TestScore('田中',42,32,22)
32 
33#メソッドculc_testの呼び出し
34person_1.culc_test()

NEXT>>第4章 クラス変数とインスタンス変数

f