This post was updated 857 days ago and some of the ideas may be out of date.

注:需要引入types模块

一、用hasattr函数判断属性是否存在。

二、用getattr函数获取实例的属性。

三、用isinstance函数判断属性是否是方法。

import types


class Controller:
    def index(self):
        print('index')


# 动态调用的方法名
call_method_name = 'indexs'
# 实例化类
controller_object = Controller()

# 判断属性是否存在
if not hasattr(controller_object, call_method_name):
    print('The controller method ' + call_method_name + ' does not exist')
    exit()

# 获取实例属性
controller_method = getattr(controller_object, call_method_name)

# 判断是否是方法
if not isinstance(controller_method, types.MethodType):
    print('The controller method ' + call_method_name + ' does not exist')
    exit()

# 调用方法
controller_method()