getattr() 函数用于返回一个对象属性值
getattr(object, name, default=None)
class Test1(object):
def __init__(self):
self.A = 'Alex'
t = Test1()
print(getattr(t,"A"))
>>> Alex
class Test(object):
def __init__(self):
self.method_allow = ['get','post']
def dispatch(self,name): # 4. 该函数执行, 即dispatch(s,'GET')
# print(name.lower())
if name.lower() in self.method_allow: # True
handle = getattr(self,name.lower()) # 5. handle ==> s.get
return handle() # 6. s.get() 执行s.get函数
class Son(Test): # 2. 继承了Test类
def post(self):
print('post被调用了')
def get(self): # 7. 该函数被执行
print('get被调用了')
s = Son() # 1. 实例化Son对象
s.dispatch('GET') # 3. 调用对象的dispatch函数
>>>get被调用了