Jak odróżnić metodę instancji, metodę klasy, metodę statyczną lub funkcję w Pythonie 3?
Chcę rozróżnić metody i funkcje w Pythonie 3. Ponadto chcę uzyskać odpowiednią klasę, jeśli jest to metoda. Moje obecne rozwiązanie jest takie:
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
Działa, ale nie wygląda elegancko. I nie jestem pewien, czy coś przeoczyłem. Czy ktoś zna lepsze rozwiązanie?
AKTUALIZACJA 1: Chcę także uzyskać odpowiednią klasę, jeśli jest to metoda. Wiem, jak radzić sobie z metodą klasy / instancji (zobacz powyższy kod), ale jak mogę uzyskać klasę dla metody statycznej?