Python通过字符串调用方法,可以使用getattr()函数。getattr()函数可以根据传入的字符串参数,查找并调用对应的方法。是一个示例代码:
Python通过字符串调用方法,可以使用getattr()函数。getattr()函数可以根据传入的字符串参数,查找并调用对应的方法。是一个示例代码:
# 定义一个类
class TestClass:
def __init__(self):
pass
def test_method1(self):
print('test_method1')
def test_method2(self):
print('test_method2')
# 创建一个实例
obj = TestClass()
# 通过字符串调用方法
method_name = 'test_method1'
getattr(obj, method_name)() # 调用test_method1()
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(15条)