どのように私は@staticmethodが属するクラスを推測するのですか?
-
09-09-2019 - |
質問
私は、メソッド与えられ、方法が属するクラスを割り出し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 ...>
解決
staticmethodsは本当に方法はありませんので、
です。あるようstaticmethod記述子は元の関数を返します。関数がアクセスした経由でクラスを取得する方法はありません。しかし、常にクラスメソッドを使用して、とにかく方法についてstaticmethodsを使用する本当の理由はありません。
私は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
所属していません StackOverflow