当您只有一个可调用对象时,有没有办法访问方法的 class

Is there a way to gain access to the class of a method when all you have is a callable

我的代码如下:

class Foo:
    def foo(self):
        pass


class Bar:
    def foo(self):
        pass

f = random.choice((Foo().foo, Bar().foo))

如何从 f 访问 BarFoo

f.__dict__ 几乎没有帮助,但由于 repr(f) 给出了 <bound method Bar.foo of <__main__.Bar object at 0x10c6eec18>>' 这一定是可能的,但是如何呢?

每个绑定方法都有 __self__ 属性,即

instance to which this method is bound, or None

(从 here 复制)

关于绑定方法的更多信息(来自 Data Model):

If you access a method (a function defined in a class namespace) through an instance, you get a special object: a bound method (also called instance method) object. ... Bound methods have two special read-only attributes: m.__self__ is the object on which the method operates...

因此 f.__self__ 将为您提供 class 实例:

print(f.__self__) # <__main__.Foo object at 0x7f766efeee48>

type(f.__self__)f.__self__.__class__ 将为您提供类型对象:

print(type(f.__self__)) # <class '__main__.Foo'>

您只需要将 __class__ 用于 old-style classes