I want store a function in a class, then call it later. Values can be called via the instance or class, but the not functions. Here's the demo:
def my_fn(a, b):
print(a, b)
class Foo(object):
fn = my_fn
avar = 5
def later(self):
# Called as class variable works.
print(Foo.avar)
# Called as class variable works.
Foo.fn('hello', 'world')
def later2(self):
# Called as class variable works.
print(Foo.avar)
# Called via self doesn't work.
self.fn('hello', 'world')
f = Foo()
f.later()
# 5
# hello world
f.later2()
# 5
# self.fn('hello', 'world')
# TypeError: my_fn() takes 2 positional arguments but 3 were given
The error means that it was successful in accessing both the variable and function when called by class in later(): Foo.avar and Foo.fn. But when called via the instance in later2, self.avar succeeded but self.fn failed because it was given an extra argument, presumably 'self'.
Is this simply an inconsistency due to the way Python inserts self into method calls, or is there a way to call functions stored in class variables through an instance?