0
0

親子関係のWindow同士の値の渡し方

Last updated at Posted at 2024-06-08

本記事の目的

言葉の定義:
GUIプログラミングにおいて、クラス単位で実装しています。

親クラスとは、GUIプログラムにおいて、親Windowを指します。
子クラスとは、GUIプログラムにおいて、子Windowを指します。

親子Windowにおいて、内部で値を渡す場面があるため、
親子関係のWindowで親Windowが持っているメンバー変数を子Windowに渡す場合の事例を示す
Pythonにおいて、実践で良く使う手法なので、覚えておいた方が良いと思います。

以下は、子供の血液型を判断する事例です。

class Father:
    def __init__(self, blood_type) -> None:
        self.blood_type = blood_type

class Mother:
    def __init__(self, blood_type) -> None:
        self.blood_type = blood_type

class Child:
    # AB型は考慮しない
    keys = [
        ['A', 'B'],
        ['A', 'O'],
        ['B', 'O'],
        ['A', 'A'],
        ['B', 'B'],
        ['O', 'O']
    ]
    values = [
        ['A', 'B', 'AB', 'O'], # rule1
        ['A', 'O'],            # rule2
        ['B', 'O'],            # rule3
        ['A', 'O'],            # rule4
        ['B', 'O'],            # rule5
        ['O'] # rule6
    ]
    # 生殖ルール
    blood_dict = {tuple(k): v for k, v in zip(keys, values)}

    def __init__(self, father, mother) -> None:
        self.father = father
        self.mother = mother

    def get_blood_type(self):
        # 両親の血液型
        parents = tuple(sorted([self.father.blood_type, self.mother.blood_type]))
        # 生まれてくる子供の血液型
        child_blood_type = Child.blood_dict[parents]
        
        print(f'生まれた子供の血液型は{child_blood_type}')

class Main:
    def __init__(self) -> None:
        self.father = Father('B')
        self.mother = Mother('A')

    def born(self):
        child = Child(self.father, self.mother)
        child.get_blood_type()

ins = Main()
ins.born()

実行結果

生まれた子供の血液型は['A', 'B', 'AB', 'O']

親クラスから子供クラスへ渡す場合(self.father, self.motherを引数として渡す)

class Main():

    def __init__(self) -> None:
        self.father = Father('B')
        self.mother = Mother('A')

    def born(self):
        child = Child(self.father, self.mother) #明示的に渡す
        child.get_blood_type()

子供クラス側は、引数で受け取る

class Child():
    def __init__(self, father, mother) -> None:
        self.father = father
        self.mother = mother

引数がたくさんある場合は、
単にselfのみを渡して、使う側で、引き取るもののみ定義して使うのも良いかと思います。

class MainWindow():
    def __init__(self) -> None:
        # GUIでほかに設定するパラメータが多くある場合
        self.hoge = HogeClass()
        self.buzz = BuzzClass()
        self.foo = FooClass()
        self.bar = BarClass()

    def ShowResults(self):
        child = ChildWindow(self) # selfのみ
        child.showSubWindow()

受けとるクラス

class ChildWindow():
    def __init__(self, main_winodow_param) -> None:
        self.param_1 = main_winodow_param.param_1
        self.param_2 = main_winodow_param.param_2
    def ShowSubWindow():
        pass
0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0