簡體   English   中英

不了解Python中的這一行代碼?

[英]Do not understand this line of code in Python?

我正在閱讀由一些經驗豐富的程序員編寫的一些代碼,但我不理解其中的一部分。 不幸的是,我是Python編程的新手。

這是使我感到困惑的代碼行:

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

概括地說,我將再次重寫它

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

這部分最讓我感到困惑:

(RealWorldScenario(newscenario))

如果有人可以給我詳盡的描述,那將非常有幫助。

謝謝

這與:

# 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()

由於命名或類的復雜性,它可能看起來令人困惑,但這與以下內容基本相同:

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

因此,在此示例中:

  1. 首先用'bar'實例化一個list
    • 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()方法。

從外面工作,我們有

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

要么

variable = SomethingConfusing.method()

我們得出結論, SomethingConfusing是一個帶有稱為method的方法的對象

我們還知道什么? 好吧,真的

OneConcreteClass(OneClass(anotherVariable))

要么

OneConcreteClass(SomethingElseConfusing)

OneConreteClass因此是一個具體的類,其發生在其另一個目的__init__方法,具體類型的東西OneClass已初始化與OneClass(anotherVariable)

有關更多詳細信息,請參見Dive into python此處

在Python中,幾乎所有東西都是Object

因此,當我們創建對象的實例時,我們將執行以下操作:

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

或obj = ClassName(Args)#此處將args傳遞給構造函數

如果您的類具有任何稱為method()成員

您可以按照以下方式進行操作:

obj.method()

要么

ClassName().method()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM