簡體   English   中英

在以下代碼中,為什么執行的最后一行給出錯誤?

[英]In the following code why does the last line of execution give an error?

在以下代碼中,為什么執行的最后一行給出錯誤? x.bf()中的點運算符不應該將實例'x'傳遞給函數bf(如x.af()那樣)嗎?

class A:
    a = 6
    def af (self):
        return "Hello-People"

class B:
    b = 7
    def bf (self):
        return "Bye-People"

>>> x = A()
>>> b = B()
>>> x.bf = B.bf
>>> x.bf()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bf() missing 1 required positional argument: 'self'

x.bf = B.bf是您的錯誤,因為B是類,而不是對象的實例。

您不能直接將x.bf分配給該類。 您需要將x.bf分配給實例'b.bf'或正確實例化該類

即。 將該行更改為:

# Where we instantiated class B and invoke bf via lazy loading (loading at the last possible minute)
x.bf = B().bf 

要么

# Use the existing instance of B and call bf
x.bf = b.bf

更多信息:

  1. A和B是您的班級。 在您實例化它們之前,它們不會執行任何操作。
  2. x和b是您的對象實例。 x是A的實例,b是B的實例
  3. 每當實例化一個類時,都需要遵循其構造函數簽名。 在這種情況下,除了self之外,這些類不需要任何其他參數。 但是,只有通過()調用該類時,才會傳遞self。

    'x = A()'和'b = B()'符合該簽名

    您遇到的錯誤基本上是python,告訴您您在不傳遞必需變量的情況下調用了某些內容,函數或類。

暫無
暫無

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

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