我想知道在 Python 中是否有可能通过使用它的字符串名称在不同的函数中找到一个方法。
在一个函数中,我传入了一个方法:
def register(methods):
for m in methods:
messageType = m.__name__
python_client_socket.send(messageType)
register(Foo)
在接受发送过来的字符串的不同方法中,我希望能够将数字与字典中的方法相关联(即 methodDict = {1: Foo, 2:Bar, etc. ..}
)
Python有没有办法从字符串中找到方法?
最佳答案
如果您确定方法名称(请不要将其用于任意输入):
getattr(someobj, methodDict[someval])
关于python - 使用方法名称字符串检索方法? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3105684/