문제

나는 구현하려고한다 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 ...>
도움이 되었습니까?

해결책

정적 메드는 실제로 방법이 아니기 때문입니다. 정적 메드 디스크립터는 원래 함수를 그대로 반환합니다. 함수에 액세스 한 클래스를 얻는 방법은 없습니다. 그러나 어쨌든 메소드에 정적 메드를 사용해야 할 이유는 없으며 항상 클래스 메드를 사용하십시오.

정적 메드에 대해 찾은 유일한 용도는 기능 객체를 클래스 속성으로 저장하고 메소드로 바꾸지 않는 것입니다.

다른 팁

나는 실제로 나 자신을 데려 오는 데 어려움이있다 추천하다 이것은하지만 적어도 간단한 경우에는 효과가있는 것 같습니다.

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top