python - 以通用或抽象的方式调用对象的方法
问题描述
我目前正在学习 Python 并试图简化我的代码。我的场景是这样的:
- “Person”类包含 50 个不同名称的函数
- 在“Bla”类中,我想根据字典中的条目调用这 50 个函数,但我试图避免编码 50 种不同的情况(如果... elif...else)
- 我的想法是在“Bla”类中有一个函数,它根据一个参数(我在dict中的函数名)决定要执行“Person”类的哪个函数
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()
解决方案
您可以使用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
不调用该方法,因此您必须添加括号才能执行此操作。
推荐阅读
- python - 使用 Docker API for Python 时出现“URL 超出最大重试次数:/v1.35/containers/create”错误
- react-native - 如何使用 react-native-svg 和 Animated 为 gradientTransform 属性设置动画
- rust - 我如何找出命名生命周期的来源?
- maven - 如何为 Maven 配置 client-maven-plugin?
- c - Mellanox libvma:如何接收与用户空间时间相当的数据包时间戳?
- android - Android 中的 Amazon Cognito 用户池和 Facebook 登录
- javascript - 如何使用 Ajax 在 Flask 中显示返回的输入?
- python - tkinter 中的命令功能无法正常工作
- python - pandas groupby - 组名而不是数字
- javascript - slice() 不能与 jQuery 一起正常工作?