■ クラス名の最初の文字は大文字を使うことが慣行である
■ コンストラクタ
__init__
■ デストラクタ
__del__
Pythonはメモリ管理の自動化を支援する⇒従って、デストラクタを多くは使わない
■ クラスの継承
class クラス名(親クラスの名前):
子クラスで親のメソッドを呼び出すときには、super()メソッドで親を求めて呼び出す
多重継承は支援するが、なるべく使用しないことが望ましい
■ 情報隠蔽
Pythonは公式的に情報隠蔽を支援していない
(1) ただし、メンバーの名前を__(「_」2個)で始めれば実際の名前を
「_クラス名__メンバー名」に変換
eg) __second ⇒ _Time__second
これをprivateのように使用
(2) また、protectedのように使用するため(または 表現するため)、
_(「_」1個)を使用すると言う
(1)・(2)いずれの場合もクラスの外部から直接アクセスすることができた
ただし、(1)の場合、Visual Studio Codeとしてコーディングするとき、
ある程度隠されたことは感じられた(下の図を参照)
情報隠蔽の利点の一つがプログラミングの利便性であることを考えると、
ある程度意味があると思う
公式的には情報隠蔽を支援しないとしても、
メンバーを外部から直接に・自由に操作させることより、
ゲッター(Getter)とセッター(Setter)メソッドを定義することが一般的
■ 簡単な例(自作):
* Pythonのクラスの特徴を簡単に活用してみることを目的として作成したので、
実戦プログラミングとは差があり得る
class Polygon:
_center_x = 1
_center_y = 2
def __init__(self, center_x_entered, center_y_entered):
self._center_x = center_x_entered
self._center_y = center_y_entered
def area(self):
print("Unable to calculate area: unknown polygon type")
class Rectangle(Polygon):
__width = 0
__height = 0
def __init__(self, witdth_entered, height_entered):
self.__width = witdth_entered
self.__height = height_entered
def area(self):
print("The center of the rectangle is: (" + str(super()._center_x) + ", " + str(super()._center_y) + ")")
print("The area of the rectangle is: " + str(self.__width * self.__height))
class Triangle(Polygon):
__width = 0
__height = 0
def __init__(self, witdth_entered, height_entered):
self.__width = witdth_entered
self.__height = height_entered
def area(self):
print("The center of the triangle is: (" + str(super()._center_x) + ", " + str(super()._center_y) + ")")
print("The area of the triangle is: " + str(0.5 * self.__width * self.__height))
poly1 = Polygon(3, 5)
rect1 = Rectangle(5, 7)
tri1 = Triangle(3, 4)
print()
rect1.area()
tri1.area()
print()
print("The x-coordinate of the center of the polygon (directly): " + str(poly1._center_x))
print("The x-coordinate of the center of the triangle (directly): " + str(tri1._center_x)) #like protected
print("The height of the rectangle (directly): " + str(rect1._Rectangle__height)) #like private
| cs |
実行結果:
The center of the rectangle is: (1, 2)
The area of the rectangle is: 35
The center of the triangle is: (1, 2)
The area of the triangle is: 6.0
The x-coordinate of the center of the polygon (directly): 3
The x-coordinate of the center of the triangle (directly): 1
The height of the rectangle (directly): 7
参考:
参考書籍(韓国の本):
파이썬 정복(Python征服)
초판발행(初版発行):2018年04月02日
지은이(著者):김상형
펴낸곳(出版社):한빛미디어(주)
参考サイト(韓国語のサイト):
https://brownbears.tistory.com/112
https://lambda2.tistory.com/3
0 件のコメント:
コメントを投稿