Python 如何推断@staticmethod所属的类?

Python 如何推断@staticmethod所属的类?,python,decorator,static-methods,inspect,Python,Decorator,Static Methods,Inspect,我试图实现interferu class函数,在给定一个方法的情况下,该函数计算出该方法所属的类 到目前为止,我有这样的想法: import inspect def infer_class(f): if inspect.ismethod(f): return f.im_self if f.im_class == type else f.im_class # elif ... what about staticmethod-s? else:

我试图实现
interferu class
函数,在给定一个方法的情况下,该函数计算出该方法所属的类

到目前为止,我有这样的想法:

import inspect

def infer_class(f):
    if inspect.ismethod(f):
        return f.im_self if f.im_class == type else f.im_class
    # elif ... what about staticmethod-s?
    else:
        raise TypeError("Can't infer the class of %r" % f)
它对@staticmethod-s不起作用,因为我没有办法实现这一点

有什么建议吗

下面是动作中的
推断类

>>> class Wolf(object):
...     @classmethod
...     def huff(cls, a, b, c):
...         pass
...     def snarl(self):
...         pass
...     @staticmethod
...     def puff(k,l, m):
...         pass
... 
>>> print infer_class(Wolf.huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().huff)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf().snarl)
<class '__main__.Wolf'>
>>> print infer_class(Wolf.puff)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in infer_class
TypeError: Can't infer the class of <function puff at ...>
类Wolf(对象): ... @类方法 ... def蒸汽吞吐(cls、a、b、c): ... 通过 ... def咆哮(自我): ... 通过 ... @静力学方法 ... def喷射(k、l、m): ... 通过 ... >>>打印推断类(Wolf.huff) >>>打印推断类(Wolf().huff) >>>打印推断类(Wolf.snarl) >>>打印推断类(Wolf().snarl) >>>打印推断类(Wolf.puff) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第6行,在推断类中 TypeError:无法推断的类别
这是因为静态方法实际上不是方法。staticmethod描述符按原样返回原始函数。无法获取用于访问函数的类。但是没有真正的理由对方法使用staticmethods无论如何,总是使用classmethods


我发现staticmethods的唯一用途是将函数对象存储为类属性,而不是将它们转换为方法。

我很难真正推荐这一点,但它似乎确实适用于简单的情况,至少:

import inspect

def crack_staticmethod(sm):
    """
    Returns (class, attribute name) for `sm` if `sm` is a
    @staticmethod.
    """
    mod = inspect.getmodule(sm)
    for classname in dir(mod):
        cls = getattr(mod, classname, None)
        if cls is not None:
            try:
                ca = inspect.classify_class_attrs(cls)
                for attribute in ca:
                    o = attribute.object
                    if isinstance(o, staticmethod) and getattr(cls, sm.__name__) == sm:
                        return (cls, sm.__name__)
            except AttributeError:
                pass

有了源代码,就可以读取父类。你为什么需要这个?您想完成什么?假设我想编写一个函数,临时存根一个函数或一个方法(为了测试目的,拦截调用或其他)。要做到这一点,我需要两个要素:包含函数的对象和函数名,这样我就可以执行
setattr(obj,func\u name,my\u stub)
。如果f是一个模块级函数,我使用
inspect.getmodule(f)
来获取对象,并使用
f.\uu name\uu
来获取其名称。对于类方法和实例方法,我使用上面的代码。对于静态方法,我似乎运气不好。-1:“但是没有真正的理由对方法使用静态方法,始终使用类方法。”你是指instancemethods还是classmethods?staticmethods有一些有效的用例,有时使用它们有“真正的理由”。我感兴趣的是,在哪里staticmethod比classmethod更可取?正如我所说,唯一引人注目的用例是将函数存储为类属性。(我不认为“但我不喜欢CLS参数”一个令人信服的论点)+ 1同意。除了将函数对象存储为类attr.或者可能只有一行:next((sys.modules[sm.\uu模块中的k代表k,v).\uu dict\uuu.items()如果getattr(v,sm.\uu name\uu,None)是sm),则无)之外,我在Python中也从未见过staticmethod的用途