Last active
March 3, 2024 13:56
-
-
Save ftnext/65f029f9df8c69273a0d9c03f8553a80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
>>> HogeTranslator().foo(1) | |
MyTranslator foo | |
108 | |
>>> HogeTranslator().foo(-1) | |
MyTranslator foo | |
Translator foo | |
42 | |
""" | |
class Translator: | |
""" | |
>>> Translator().foo(1) | |
Translator foo | |
42 | |
""" | |
def foo(self, number): | |
print("Translator foo") | |
return 42 | |
class MyTranslator(Translator): | |
def foo(self, number): | |
""" | |
>>> MyTranslator().foo(1) | |
MyTranslator foo | |
108 | |
>>> MyTranslator().foo(-1) | |
MyTranslator foo | |
Translator foo | |
42 | |
""" | |
print("MyTranslator foo") | |
# print(self.__class__) | |
if number > 0: | |
return 108 | |
# 以下はメソッド代入を可能にするが、SpecialMyTranslatorで無限再帰エラーとなる | |
# return super(self.__class__, self).foo(number) | |
if not isinstance(self, MyTranslator): | |
# メソッド代入をサポート(かつ、無限再帰が起きない) | |
return super(self.__class__, self).foo(number) | |
return super(MyTranslator, self).foo(number) | |
class HogeTranslator(Translator): ... | |
HogeTranslator.foo = MyTranslator.foo | |
class SpecialMyTranslator(MyTranslator): | |
""" | |
>>> SpecialMyTranslator().foo(1) | |
MyTranslator foo | |
108 | |
>>> SpecialMyTranslator().foo(-1) | |
MyTranslator foo | |
Translator foo | |
42 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment