我試圖實現infer_class
函數,給定一個方法,計算出該方法所屬的類。如何推斷@staticmethod屬於的類?
到目前爲止,我有這樣的事情:
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)
它不爲@靜態方法的工作,因爲我無法想出一個辦法來實現這一目標。
有什麼建議嗎?
這裏是在行動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 ...>
你的源代碼,你可以讀父類。你爲什麼需要這個?你想達到什麼目的? – 2009-06-04 09:52:12
假設我想編寫一個臨時存儲函數或方法的函數(爲了測試目的攔截調用或其他函數)。爲了做到這一點,我需要兩個成分:包含函數的對象和函數名,以便我可以執行`setattr(obj,func_name,my_stub)`。如果f是一個模塊級的函數,我使用`inspect.getmodule(f)`獲取對象和`f .__ name__`來獲取它的名字。對於類方法和實例方法,我使用上面的代碼。對於靜態方法,我看起來很失敗。 – 2009-06-04 17:45:57