字符串转化成方法
import importlib
def find_method_by_str(method_path):
"""通过字符串,寻找方法"""
if not method_path:
return None
methods = method_path.split(".")
_module = importlib.import_module(".".join(methods[:-1]))
_method = getattr(_module, methods[-1], None)
if not callable(_method):
return None
return _method
方法转存字符串
Python3的方式
def get_caller_location(caller):
location = "{}.{}".format(caller.__module__, caller.__qualname__)
return location
Python2的方式
import inspect
def get_caller_location(caller):
if inspect.isclass(caller) or inspect.isfunction(caller):
location = "{}.{}".format(caller.__module__, caller.__name__)
elif inspect.ismethod(caller):
fn_cls = caller.im_class
location = "{}.{}.{}".format(caller.__module__, fn_cls.__name__, caller.__name__)
else:
raise TypeError("not support type {}".format(type(caller)))
return location