練習問題 解答

10.9 練習問題 解答

問1

① ×:スーパークラスからはいくつでもサブクラスを作成できる。
② ×:サブクラスの継承もとになるスーパークラスは複数選べる。
③ ○
④ ×:サブクラス内でスーパークラスと同じ定義のメソッドを記述できる。
⑤ ×:必ずオーバーロードするため定義し直されなければならない。

問2

① ×:クラスYがクラスXのスーパークラスになる。
② ×:スーパークラスと同じ名前の変数をサブクラスでも定義できる。
③ ○:引数ありのコンストラクタが必要になる。
④ 〇:super()関数で呼び出しているため必要になる。
⑤ ○:スーパークラスに同じ名前のメソッドが定義されている必要はない。

問3

① A ② a1 ③ B ④ b1

⑤ A ⑥ a2 ⑦ B ⑧ b2

出力結果

1[クラスSampleA]の a1 のコンストラクタ
2[クラスSampleB]の b1 のコンストラクタ
3[クラスSampleA]の a2 のコンストラクタ
4[クラスSampleB]の b2 のコンストラクタ

問4

1class Books:
2 
3    def __init__(self,title='未定',price=0):
4        self.__title = title
5        self.__price = price
6        print('本を作成しました。')
7 
8    #ゲッターの定義
9    @property
10    def getTitle(self):
11        return self.__title
12 
13    #セッターの定義
14    @getTitle.setter
15    def setTitle(self,value):
16        self.__title = value
17        print('この本のタイトルは' + self.__title +'にしました。')
18 
19    #ゲッターの定義
20    @property
21    def getPrice(self):
22        return self.__price
23 
24    #セッターの定義
25    @getPrice.setter
26    def setPrice(self,value):
27        self.__price = value
28        print('この本の価格は' + str(self.__price) + '円にしました。')
29 
30 
31#以下にTextBooksクラスを定義しなさい
32class TextBooks(Books):
33 
34    def __init__(self,subject='未定'):
35        super().__init__()
36        self.__subject = subject
37 
38    #ゲッターの定義
39    @property
40    def getSubject(self):
41        return self.__subject
42 
43    #セッターの定義
44    @getSubject.setter
45    def setSubject(self,value):
46        self.__subject = value
47        print('この本の教科を' + self.__subject + 'にしました。')

問5

1import abc
2 
3class Books(metaclass=abc.ABCMeta):
4 
5    def __init__(self,title='未定',price=0):
6        self.__title = title
7        self.__price = price
8        print('本を作成しました。')
9 
10    #ゲッターの定義
11    @property
12    def getTitle(self):
13        return self.__title
14 
15    #セッターの定義
16    @getTitle.setter
17    def setTitle(self,value):
18        self.__title = value
19        print('この本のタイトルは' + self.__title +'にしました。')
20 
21    #ゲッターの定義
22    @property
23    def getPrice(self):
24        return self.__price
25 
26    #セッターの定義
27    @getPrice.setter
28    def setPrice(self,value):
29        self.__price = value
30        print('この本の価格は' + str(self.__price) + '円にしました。')  
31 
32    @abc.abstractmethod
33    def showBook(self):
34        pass
35 
36#以下にTextBooksクラスを定義しなさい
37class TextBooks(Books):
38 
39    def __init__(self,subject='未定'):
40        super().__init__()
41        self.__subject = subject
42 
43    #ゲッターの定義
44    @property
45    def getSubject(self):
46        return self.__subject
47 
48    #セッターの定義
49    @getSubject.setter
50    def setSubject(self,value):
51        self.__subject = value
52        print('この本の教科を' + self.__subject + 'にしました。')              
53 
54    def showBook(self):
55        print('教科:' + self.__subject)
56        print('タイトル:' + self.getTitle)
57        print('価格:' + str(self.getPrice) + '円')

NEXT>> 第11章 モジュールファイルの作成

f