The following code works:
class Foo:
def run_this(self):
print("ran this")
ff = Foo()
method = getattr(ff, "run_this")
method()
--
run_this
But I don't understand why. If getattr returns a function object should I need to pass self
to the object as the first argument. It seems that method
is not a function object after all, but I'm not sure what it is then. Why does self get passed when I call method()
?
The docs say only
getattr(object, name[, default]) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
So they answer the "what happens" question, but not the question of why it works this way.