python利用字符串名称动态调用函数或对象方法
1.eval
def func_eval():
print('func by eval')
func_name = "func_eval"
eval(func_name)()
# func by eval
2.getattr
class Student:
school = "gaofeng"
__region = "zhejiang"
def __init__(self,height,age):
self.height = height
self.__age = age
def work(self,company):
print("work in",company)
def play(self):
print("want play,cannot play")
@classmethod
def gotoschool(cls):
print("goto",cls.school)
@staticmethod
def study():
print("good good study")
if __name__ == '__main__':
stu = Student(177.0,25)
getattr(stu,'study')()
getattr(Student, 'study')()
getattr(stu, 'gotoschool')()
getattr(Student, 'gotoschool')(