我想将一个函数存储在一个类中,然后再调用它。可以通过实例或类来调用值,但不能通过函数来调用。这是演示:
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
该错误表示在稍后的类(Foo.avar和Foo.fn)中被类调用时,它可以成功访问变量和函数。但 在稍后的2中通过实例调用时,self.avar成功,但self.fn失败,因为给了它一个额外的参数,大概是“ self”。
这仅仅是由于Python将self插入方法调用中而导致的不一致吗?还是有办法通过实例来调用存储在类变量中的函数?