首页 > 解决方案 > 以通用或抽象的方式调用对象的方法

问题描述

我目前正在学习 Python 并试图简化我的代码。我的场景是这样的:

class Person:
    def walk(self):
        print('do something')

    def wink(self):
        print('do something else')

class Bla:
    def abstract_function(data):
        for key in data:
            # execute function in class Person
            p = Person()
            # this is where i need help - how to execute the function of "Person" based on the entry in data?
            p.key()

标签: pythonpython-3.x

解决方案


您可以使用getattr(object, method). 这将从您的对象中检索给定名称的方法。在你的情况下

class Person:
    def walk(self):
        print('do something')

    def wink(self):
        print('do something else')

class Bla:
    def abstract_function(data):
        for key in data:
            p = Person()
            getattr(p, key)()

getattr不调用该方法,因此您必须添加括号才能执行此操作。


推荐阅读