Python総合学習【オブジェクト指向編】

クラス
クラスを使用した乗算処理について解説します。
ソース
クラス
#coding: shift_jis
class MyCls():
X = 0
Y = 0
Z = 0
def MyMethod(self):
self.Z = self.X * self.Y
メイン
#coding: shift_jis
import MyCls
A = MyCls.MyCls()
A.X = 2
A.Y = 3
A.MyMethod()
print(A.Z)
input()
変数=値
メンバ変数を宣言します。
def メソッド名(self):
処理
メソッドを宣言します。
変数 = ファイル名.クラス名
クラスのインスタンスを生成します。
コンストラクタ
コンストラクタを使用して、オブジェクト指向の特徴であるカプセル化について解説します。
ソース
クラス
#coding: shift_jis
class MyCls:
__X = ""
def __init__(self,Y):
self.__X = Y
def MyMethod(self):
print(self.__X)
メイン
#coding: shift_jis
import MyCls
A = MyCls.MyCls("コンストラクタ")
A.MyMethod()
input()
__変数=値
ローカル変数を宣言します。
def __init__(self):
処理
コンストラクタを宣言します
プロパティ
プロパティを使用して、オブジェクト指向の特徴であるカプセル化について解説します。
ソース
クラス
#coding: shift_jis
class MyCls:
__X = ""
@property
def MyProperty(self):
return self.__X
@MyProperty.setter
def MyProperty(self, Y):
self.__X = Y
メイン
#coding: shift_jis
import MyCls
A = MyCls.MyCls()
A.MyProperty = "プロパティ"
print(A.MyProperty)
input()
@property
def プロパティ名(self):
return 値
内部変数を返却します。
@プロパティ名.setter
def プロパティ名(self, 値)
内部変数 = 値
内部変数に値を設定します。
継承
オブジェクト指向の特徴である継承について解説します。
ソース
親クラス
#coding: shift_jis
class ParentCls:
def ParentMethod(self):
print("親クラス")
子クラス
#coding: shift_jis
import ParentCls
class ChildCls(ParentCls.ParentCls):
def ChildMethod(self):
print("子クラス")
メイン
#coding: shift_jis
import ChildCls
A = ChildCls.ChildCls()
A.ParentMethod()
A.ChildMethod()
input()
class クラス名(継承元クラス名)
クラスを継承します。
オーバーライド
オーバーライドを使用して、オブジェクト指向の特徴であるポリモーフィズムについて解説します。
ソース
親クラス
#coding: shift_jis
class ParentCls:
def MyMethod(self):
print("親クラス")
子クラス
#coding: shift_jis
import ParentCls
class ChildCls(ParentCls.ParentCls):
def MyMethod(self):
print("子クラス")
メイン
#coding: shift_jis
import ChildCls
A = ChildCls.ChildCls()
A.MyMethod()
input()