Consider the following code (which works)
class AAA:
def run(self):
getattr(AAA, 'meth')(what='hello')
@staticmethod
def meth(what):
print(what)
AAA().run()
I will need to use in meth()
an attribute of the instanced object, so meth()
cannot be static anymore. I tried to do
class AAA:
def __init__(self):
self.who = 'John'
def run(self):
getattr(AAA, 'meth')(what='hello')
def meth(self, what):
print(f"{what} {self.who}")
AAA().run()
but this crashes with
Traceback (most recent call last):
File "C:/scratch_15.py", line 12, in <module>
AAA().run()
File "C:/scratch_15.py", line 7, in run
getattr(AAA, 'meth')(what='hello')
TypeError: meth() missing 1 required positional argument: 'self'
I then corrected my code to
class AAA:
def __init__(self):
self.who = 'John'
def run(self):
getattr(AAA, 'meth')(self, what='hello')
def meth(self, what):
print(f"{what} {self.who}")
AAA().run()
# outputs "hello John"
Why do I have to explicitly pass self
when calling a method in the situation above?