【发布时间】:2021-10-02 05:15:00
【问题描述】:
我有两个 Python 类实例(我简化了逻辑以使其更短)
class First:
def first_p(self):
print('test')
first_instance = First()
second_instance = First()
现在我需要选择使用哪一个实例(我可以通过在 if/else 中重复代码来完成)
if x:
second.first_p()
else:
first.first_p()
但我想知道我怎么能这样做(它不起作用)
'{}'.first_p().format(second)
【问题讨论】:
-
@Machina OP 正在尝试动态选择哪个实例 - 而不是属性 AFAIU。
-
这里的正确方法是创建一个显式映射,即将字符串映射到所需对象的
dict。
标签: python python-class