LoginSignup
1
0

More than 1 year has passed since last update.

Pythonで親を飛ばして親の親のメソッドを呼ぶ

Last updated at Posted at 2022-10-09

要は親のメソッドは完全にオーバーライドしたいけど、親の親のメソッドは使いたい場合

class Grandparent:
    def name(self, text):
        return text + '>サンデーサイレンス'

class Parent(Grandparent):
    def name(self, text):
        return super().name(text + '>ステイゴールド')

class My(Parent):
    def name(self, text):
        return super().name(text)

name = My().name('ゴールドシップ')
print(name)

結果は当然

ゴールドシップ>ステイゴールド>サンデーサイレンス

親を飛ばして、親の親を呼びたい場合

class Grandparent:
    def name(self, text):
        return text + '>サンデーサイレンス'

class Parent(Grandparent):
    def name(self, text):
        return super().name(text + '>ステイゴールド')

class My(Parent):
    def name(self, text):
        return super(Parent, self).name(text)

name = My().name('ゴールドシップ')
print(name)

結果

ゴールドシップ>サンデーサイレンス

キモはここです

return super(Parent, self).name(text)
1
0
0

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
1
0