Python中如何将字符串转换成可调用的方法

部署运行你感兴趣的模型镜像

字符串转化成方法

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

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值