【问题标题】:How do I infer the class to which a @staticmethod belongs?如何推断 @staticmethod 所属的类?
【发布时间】:2010-10-31 06:13:49
【问题描述】:

我正在尝试实现infer_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,因为我无法想出实现此目的的方法。

有什么建议吗?

infer_class 正在行动:

>>> 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 ...>

【问题讨论】:

  • 你有源码,你可以阅读父类。你为什么需要这个?你想完成什么?
  • 假设我想编写一个临时存根函数或方法的函数(以拦截调用或其他任何东西,用于测试目的)。为了能够做到这一点,我需要两个要素:包含函数的对象和函数名称,这样我就可以做到setattr(obj, func_name, my_stub)。如果 f 是模块级函数,我使用inspect.getmodule(f) 获取对象,使用f.__name__ 获取其名称。对于类方法和实例方法,我使用上面的代码。对于静态方法,我似乎不走运。

标签: python decorator static-methods inspect


【解决方案1】:

那是因为静态方法真的不是方法。静态方法描述符按原样返回原始函数。无法获取访问该函数的类。但是无论如何都没有真正的理由为方法使用静态方法,始终使用类方法。

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

【讨论】:

  • -1: "但是无论如何都没有真正的理由为方法使用静态方法,总是使用类方法。"你的意思是实例方法还是类方法?静态方法有有效的用例,有时有“真正的理由”使用它们。
  • 我很感兴趣静态方法在哪里比类方法更可取?正如我所说,唯一引人注目的用例是将函数存储为类属性。 (而且我不认为“但我不喜欢 cls 参数”是一个令人信服的论点)
  • +1 同意。除了将函数对象存储为类属性之外,我也从未见过 Python 中使用 staticmethod。
【解决方案2】:

我很难让自己真正推荐这个,但它似乎确实适用于简单的案例,至少:

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

【讨论】:

  • 或者可能只有 1 行: next((k for k,v in sys.modules[sm.__module__].__dict__.items() if getattr(v,sm.__name__,None) 是 sm ),无)
猜你喜欢
  • 1970-01-01
  • 2020-04-27
  • 2019-04-28
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 2023-02-11
相关资源
最近更新 更多