【问题标题】:Do not understand this line of code in Python?看不懂Python中的这行代码?
【发布时间】:2013-11-01 21:03:43
【问题描述】:

我正在阅读一些有经验的程序员编写的一段代码,但我不明白其中的一部分。不幸的是,我是 Python 编程新手。

这是让我困惑的代码行:

realworld = ConcreteRealWorldScheduler(RealWorldScenario(newscenario)).schedule()

为了概括,我将再次重写它

variable = OneConcreteClass(OneClass(anotherVariable)).method()

这部分最让我困惑:

(RealWorldScenario(newscenario))

如果有人能给我一个详尽的描述,那将非常有帮助。

谢谢

【问题讨论】:

  • RealWorldScenario(newscenario) 表示RealWorldScenario 类的对象正在使用变量newscenario 构造。
  • 我不知道为什么内部实例会让你感到困惑,但外部实例却不会。
  • 你知道python中的类和__init__方法吗?

标签: python class oop abstract-class


【解决方案1】:

这与:

# New object, newscenario passed to constructor
world_scenario = RealWordScenario(newscenario)
# Another new object, now world_scenario is passed to constructor
scheduler = ConcreteRealWorldScheduler(world_scenario)
# Call the method
variable = scheduler.method()

【讨论】:

    【解决方案2】:

    由于命名或类的复杂性,它可能看起来令人困惑,但这与以下内容基本相同:

    foo = set(list('bar')).pop()
    

    所以,在这个例子中:

    1. 首先list'bar' 实例化
      • list('bar') == ['b', 'a', 'r']
    2. 接下来从列表中创建一个集合
      • set(['b', 'a', 'r']) == {'a', 'b', 'r'}
    3. 然后我们使用setpop()方法
      • {'a', 'b', 'r'}.pop() 将返回 'a' 并将 set 保留为 {'b', 'r'}

    所以你给定的代码行也是如此:

    realworld = ConcreteRealWorldScheduler(RealWorldScenario(newscenario)).schedule()
    
    1. 首先使用newscenario 实例化一个新的RealWorldScenario
    2. 接下来,使用 RealWorldScenario 实例实例化 ConcreteRealWorldScheduler
    3. 最后调用ConcreteRealWorldScheduler实例的schedule()方法。

    【讨论】:

      【解决方案3】:

      相反,我们从外部工作

      variable = OneConcreteClass(OneClass(anotherVariable)).method()
      

      variable = SomethingConfusing.method()
      

      我们得出结论SomethingConfusing 是一个对象,其方法名为method

      我们还知道什么? 嗯,真的

      OneConcreteClass(OneClass(anotherVariable))
      

      OneConcreteClass(SomethingElseConfusing)
      

      OneConreteClass 因此是一个具体的类,它在其__init__ 方法中采用另一个对象,特别是OneClass 类型的东西,它已用OneClass(anotherVariable) 初始化

      更多详情请参阅Dive into pythonhere

      【讨论】:

        【解决方案4】:

        在 Python 中,几乎所有内容都是 Object

        所以当我们为一个对象创建实例时,我们会这样做:

        obj = ClassName()  # class itself an object of "Type"
        

        或 obj = ClassName(Args) # 这里将args传递给构造函数

        如果你的班级有任何成员叫method()

        你可以这样做:

        obj.method()
        

        ClassName().method()
        

        【讨论】:

          猜你喜欢
          • 2021-08-22
          • 1970-01-01
          • 2017-05-16
          • 1970-01-01
          • 1970-01-01
          • 2017-10-13
          • 2023-03-28
          • 1970-01-01
          • 2011-05-10
          相关资源
          最近更新 更多