【问题标题】:Can you initialise multiple instances of a class in one single line?你能在一行中初始化一个类的多个实例吗?
【发布时间】:2021-11-10 17:19:15
【问题描述】:

假设我想在初始化一个类的多个实例时压缩我的代码。

此代码有效:

from ipywidgets import Output,HBox
out1 = Output(layout={'border': '1px solid black'})
out2 = Output(layout={'border': '1px solid black'})
out3 = Output(layout={'border': '1px solid black'})

with out1: display('here is out1')
with out2: display('here is out2')
with out3: display('here is out3')

display(HBox([out1,out2,out3]))

现在我想要的是不必重复三遍 out1、out2 和 out3 的初始化。

这当然不行:

out1=out2=out3=Output(layout={'border': '1px solid black'})

因为这三个outs 是同一个对象。

想象一下你有 10 次初始化要做,有什么好的 Python 方式来完成它而无需编写 10 行代码?

其他对我没有帮助的咨询: Automatically initialize multiple instance of class Can one initialize multiple variables of some type in one line? Python creating multiple instances for a single object/class

【问题讨论】:

  • 循环并添加到列表或字典中?
  • 基于意见,但您应该更关心代码的清晰度而不是行数。您是否考虑过循环或列表理解,或工厂构造函数? en.wikipedia.org/wiki/Factory_method_pattern
  • out1, out2, out3 = [Output(layout={'border': '1px solid black'}) for i in range(3)]?
  • 我非常喜欢这个答案。谢谢。

标签: python class initialization instance


【解决方案1】:

在列表中创建Output 对象,然后您可以遍历列表:

outputs = [Output(layout={'border': '1px solid black'}) for _ in range(3)]

for i, out in enumerate(outputs, 1):
    with out:
        display(f"here is out{i}")

display(HBox(outputs))

【讨论】:

    【解决方案2】:

    如果您不介意将这些变量保存在列表中, 我会考虑一个调用函数的循环

    from ipywidgets import Output,HBox
    
    def get_obj():
        return Output(layout={'border': '1px solid black'})
    
    def do_display(out, i):
        with out: display(f"here is out{i}")
    
    outs = [get_obj() for _ in range(3)]
    for i, out in enumerate(outs):
        do_display(out, i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多