【问题标题】:Python OOP select instance dynamicallyPython OOP 动态选择实例
【发布时间】: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


【解决方案1】:
'{}'.format(second_instance.p() if x else first_instance.p())

【讨论】:

    【解决方案2】:

    我认为您正在尝试实现这样的目标:

    class First:
        def first_p(self):
            return 'test' 
    
    
    first_instance = First()
    second_instance = First()
    
    print(f"{ (first_instance if x else second_instance).first_p() }")
    

    因为“'{}'.first_p().format(second)”没有任何意义(因为您调用first_p 就好像它是Str 中的一个方法)

    【讨论】:

      【解决方案3】:

      我认为这个问题可以简化为“如何根据字符串访问变量?”

      其实是可以的,取决于范围:

      # global scope
      instance = globals()[second]
      instance.first_p()
      

      参考:https://www.programiz.com/python-programming/methods/built-in/globals

      # local scope, such as inside a function
      instance = locals()[second]
      instance.first_p()
      

      参考:https://www.programiz.com/python-programming/methods/built-in/locals

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 2011-10-26
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-20
        相关资源
        最近更新 更多