LESSON 25 ・ クラス
クラス
情報がばらばらになる問題
names = ["Mary", "Mike", "Tom"]
scores = [65, 90, 85]
for i in range(len(names)):
print(names[i], scores[i])
複数人の名前とテストの点数を扱うには、二つのリストが必要になります。しかし、名前と点数をばらばらに扱うことになりわかりづらいです。
クラスで情報をまとめる
class Student:
name = ""
score = 0
student = Student()
student.name = "Mary"
student.score = 65
print(student.name)
print(student.score)
クラス(class)を使えば、名前と点数のような、複数種類の値を一つにまとめて扱うことができます。
ここではStudent(生徒)クラスを作ります。クラスの中に書いたnameとscoreは、Studentクラスが持つクラス属性(class attribute)です。このように値を表す属性をデータ属性(データぞくせい, data attribute)と言います。
Student()でStudentのオブジェクトを作って変数studentに代入します。student.name = "Mary"のように代入すると、studentオブジェクト自身が持つインスタンス属性(instance attribute)が作られます。student.nameやstudent.scoreのように、オブジェクトを格納した変数名と属性名を.でつなぐことで、その属性にアクセスできます。
class Student:
name = ""
score = 0
student = Student()
student.name = "Mary"
student.score = 65
print(f"{student.name}: {student.score}点")
Mary: 65点のような形式で名前と点数を出力するにはprint(f"{student.name}: {student.score}点")と書けます。
PRACTICE
演習問題
コードを自分で書いて実行してから、答えと解説を確認しましょう。
問題1
名前と点数を持つStudentクラスを作ってください。オブジェクトを一つ作り、名前に"Mary"、点数に65を代入して、両方を表示してください。
答えと解説を見る
模範解答
class Student:
name = ""
score = 0
student = Student()
student.name = "Mary"
student.score = 65
print(student.name)
print(student.score)
クラスに名前と点数をまとめ、作成したオブジェクトのそれぞれの値へ.を使ってアクセスします。
問題2
本の題名とページ数を持つBookクラスを作ってください。オブジェクトを一つ作り、題名に"Python Guide"、ページ数に240を代入して表示してください。
答えと解説を見る
模範解答
class Book:
title = ""
pages = 0
book = Book()
book.title = "Python Guide"
book.pages = 240
print(book.title)
print(book.pages)
関連する題名とページ数を一つのBookオブジェクトにまとめています。
問題3
幅と高さを持つRectangleクラスを作ってください。幅8・高さ5のオブジェクトと、幅3・高さ9のオブジェクトを作り、それぞれの面積を表示してください。
答えと解説を見る
模範解答
class Rectangle:
width = 0
height = 0
first = Rectangle()
first.width = 8
first.height = 5
second = Rectangle()
second.width = 3
second.height = 9
print(first.width * first.height)
print(second.width * second.height)
同じクラスから複数のオブジェクトを作ると、それぞれが別の幅と高さを持てます。面積は順に40と27です。