python 如何知道一个 method 是属于哪个class ?

我希望可以判断一个 method 是属于哪个 class 的,要如何实现。

比如下面的代码,定义了一个 get_class_by_method 函数,参数是 method 接受函数类型,返回该函数归属的 class

from typing import Callable


class Work:
    def run(self):
        pass


class Reload:
    @classmethod
    def wait(cls):
        pass


def get_class_by_method(method: Callable) -> type:
    pass

比如, 通过下面的代码,获取对应的 class

get_class_by_method(Work().run)

又或者这样:

get_class_by_method(Reload.wait)

插一个子问题:
我比较喜欢 python 的 typing hint,关于 get_class_by_method 的函数返回值,我注释为 type ,但是这让我是不是很满意,有什么更好的注释选择吗?

阅读 1.8k
1 个回答

instance method 有一个 __self__ 属性:

datamodel

When an instance method object is created by retrieving a user-defined function object from a class via one of its instances, its __self__ attribute is the instance, and the method object is said to be bound. The new method’s __func__ attribute is the original function object.

When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself, and its __func__ attribute is the function object underlying the class method.

推荐问题