问题描述
我想在Python 3中区分方法和函数.此外,如果它是一个方法,我想获得相应的类.我当前的解决方案是这样的:
I want to distinguish between methods and functions in Python 3. Furthermore, I want to get the corresponding class if it is a method. My current solution is like this:
import types
import inspect
def function_or_method(f):
if inspect.ismethod(f):
if inspect.isclass(f.__self__):
print("class method")
klass = f.__self__
else:
print("instance method")
klass = f.__self__.__class__
elif inspect.isfunction(f): # function
if f.__name__ != f.__qualname__: # to distiguish staticmethod and function
print("static method")
# HOW TO GET THE CLASS
else:
print("function")
else:
print("not function or method")
class Foo():
def bari(self):
pass
@classmethod
def barc(cls):
pass
@staticmethod
def bars():
pass
def barf():
pass
function_or_method(Foo().bari) # instance method
function_or_method(Foo.barc) # class method
function_or_method(Foo.bars) # static method
function_or_method(barf) # function
它可以工作,但是看起来并不优雅.而且我不确定我是否错过了什么.有谁知道更好的解决方案?
It works, but it looks not elegant. And I am not sure whether I have missed something. Does anyone know a better solution?
更新1 :如果它是方法,我也想获得相应的类.我知道如何处理类/实例方法(请参见上面的代码),但是如何获取静态方法的类?
UPDATE 1: I also want to get the corresponding class if it is a method. I know how to deal with class/instance method(see the above code), but how can I get the class for the static method?
推荐答案
您只需要获取方法的类型,但是由于方法是描述符,因此您必须:
You just need to get the type of the method, but since methods are descriptors, you have to :
1-将类从实例中取出.2-在__dict__
中查找方法引用,而不是进行属性查找.
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'>
这篇关于如何在Python 3中区分实例方法,类方法,静态方法或函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!