如何推断@staticmethod所属的类? [英] How do I infer the class to which a @staticmethod belongs?

查看:98
本文介绍了如何推断@staticmethod所属的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现 infer_class 函数,在给定方法的情况下,该函数可以计算出该方法所属的类。



到目前为止,我有类似这样的东西:

 导入检查

def infer_class(f ):
if inspect.ismethod(f):
返回f.im_self如果f.im_class ==类型else f.im_class
#elif ... staticmethod-s呢?
else:
提高TypeError(无法推断%r的类别%f)

它不适用于@ staticmethod-s,因为我无法提出实现此目标的方法。



有什么建议吗? p>

这里是 infer_class 的作用:

 >>类Wolf(object):
... @classmethod
... def huff(cls,a,b,c):
...通过
... def snarl(self):
...通过
... @staticmethod
... def puff(k,l,m):
...通过
...
>> print infer_class(Wolf.huff)
< class ________ Wolf'>
>> print infer_class(Wolf()。huff)
< class‘__main __。Wolf’>
>>打印infer_class(Wolf.snarl)
< class ______________
>>打印infer_class(Wolf()。snarl)
< class‘__main __。Wolf’>
>>打印infer_class(Wolf.puff)
追溯(最近一次调用最近):
文件< stdin>,< module>中的第1行。
infer_class
TypeError中的文件< stdin>,第6行:无法推断<


解决方案

这是因为静态方法实际上不是方法。静态方法描述符按原样返回原始函数。无法获取通过其访问函数的类。但是无论如何,没有真正的理由对方法使用静态方法,总是使用类方法。



我发现静态方法的唯一用途是将函数对象存储为类属性,并且不要让它们变成方法。


I am trying to implement infer_class function that, given a method, figures out the class to which the method belongs.

So far I have something like this:

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)

It does not work for @staticmethod-s because I was not able to come up with a way to achieve this.

Any suggestions?

Here's infer_class in action:

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

解决方案

That's because staticmethods really aren't methods. The staticmethod descriptor returns the original function as is. There is no way to get the class via which the function was accessed. But there is no real reason to use staticmethods for methods anyway, always use classmethods.

The only use that I have found for staticmethods is to store function objects as class attributes and not have them turn into methods.

这篇关于如何推断@staticmethod所属的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆