How to distinguish an instance method, a class method, a static method or a function in Python 3?

久未见 提交于 2019-12-01 00:59:08

You just need to get the type of the method, but since methods are descriptors, you have to :

1 - Get the class out of the instance. 2 - Look up the method reference in __dict__ instead of making an attribute lookup.

E.G :

>>> f = Foo()
>>> type(f.__class__.__dict__['bari'])
<class 'function'>
>>> type(f.__class__.__dict__['barc'])
<class 'classmethod'>
>>> type(f.__class__.__dict__['bars'])
<class 'staticmethod'>
Sravan K Ghantasala

I think better way to use isfunction() method of inspect.

Syntax:

[inspect.getmembers(<module name>, inspect.isfunction)] # will give all the functions in that module

If you want to test single method, you can do so by...

inspect.isfunction(<function name>) # return true if is a function else false

There are many predicates you can use along with is function. Refer to the Python 3 documentation for inspect for a clear picture.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!