I came accross a piece of Python legacy code at work that I couldn't understand how it could work without errors. Obviously I can't write the exact code here but here is a minimal working example:
class ClassB:
def func(self, txt: str):
return self.str_to_uppercase(txt)
class ClassA(ClassB):
def str_to_uppercase(self, txt: str):
return txt.upper()
if __name__ == "__main__":
my_instance = ClassA()
print(my_instance.func("Hello, World!"))
stdout: HELLO, WORLD!
What's strange to me is that, although ClassB
is not directly inheriting from ClassA
where the instance method str_to_uppercase()
is defined, ClassB
is still able to call this method. I should also note that my linter (pylint) is complaining that str_to_uppercase()
is not defined in ClassB
. So I'm struggling to understand how the mechanics of the code works here regarding inheritence.
Secondly, this code looks strange to me. It doesn't seem very "Pythonic". So, as a second question, I was wondering in which usecases such code is useful?