簡體   English   中英

Python奇怪錯誤:“TypeError:'NoneType'對象不可調用”

[英]Python Strange Error: “TypeError: 'NoneType' object is not callable”

我正在實現一個簡單的類來表示2D矢量。 以下是相關位:

class Vector:
  def __init__( self, x, y ):
    self.vec_repr = x, y

  def __add__( self, other ):
    new_x = self.x + other.x
    new_y = self.y + other.y
    return Vector( new_x, new_y )

  def __getattr__( self, name ):
    if name == "x":
      return self.vec_repr[0]
    elif name == "y":
      return self.vec_repr[1]

后來,我有類似的東西:

a = Vector( 1, 1 )
b = Vector( 2, 2 )
a + b

我得到TypeError: 'NoneType' object is not callable 這特別奇怪,因為錯誤沒有標記為在任何特定的行上,所以我不知道在哪里看!

非常奇怪,所以我做了一些實驗,發現它發生在a+b線上。 另外,當我重新上課時,如下:

class Vector:
  def __init__( self, x, y ):
    self.x, self.y = x, y

  def __add__( self, other ):
    new_x = self.x + other.x
    new_y = self.y + other.y
    return Vector( new_x, new_y )

錯誤消失了!

我看到有很多關於類似於此的錯誤的問題 - 所有似乎都涉及某個函數名稱被某個變量覆蓋,但我不知道這發生了什么!

作為另一個線索,當我將__getattr__()的默認返回類型更改為其他東西時 - 例如str - 錯誤變為TypeError: 'str' object is not callable

關於發生了什么的任何想法? 是否有__getattr__()某些行為我不明白?

問題是你的__getattr__不會為xy以外的屬性返回任何內容,也不會引發AttributeError。 因此,當__add__方法時, __getattr__ __add__返回None ,從而返回錯誤。

您可以通過為其他屬性返回__getattr__返回值來解決此問題。 實際上,您必須確保__getattr__從其超類調用未處理的所有屬性的方法。 但是真的__getattr__在這里使用是錯誤的。 它應該謹慎使用,並且當沒有更明顯的,更高級別的解決方案可用時。 例如, __getattr__對於動態調度至關重要。 但在您的情況下, xy值是眾所周知的,並且在代碼運行之前已經定義好。

正確的解決方案是制作xy屬性,而不是實現__getattr__

@property
def x(self):
    return self.vec_repr[0]

@property
def y(self):
    return self.vec_repr[1]

暫無
暫無

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

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