4

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

2 に答える 2

3

これは、staticmethodsが実際にはメソッドではないためです。staticmethod記述子は、元の関数をそのまま返します。関数にアクセスしたクラスを取得する方法はありません。しかし、とにかくメソッドにstaticmethodsを使用する本当の理由はありません。常に、classmethodsを使用してください。

staticmethodsで私が見つけた唯一の用途は、関数オブジェクトをクラス属性として格納し、それらをメソッドに変換しないことです。

于 2009-06-04T09:09:15.810 に答える
3

私は実際にこれを推奨するのに苦労していますが、少なくとも次のような単純なケースでは機能するようです。

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
于 2009-06-08T17:55:32.587 に答える