簡體   English   中英

檢查 object 是否在確定的 class python 中

[英]Checking if an object is in a determined class python

我正在嘗試創建一個代表向量(稱為向量)和一個代表矩陣(稱為矩陣)的 class。 定義矩陣向量乘積時出現的問題:我在實際實現中看不到錯誤,但我嘗試在代碼之前添加一個檢查以引發錯誤,如果第二個元素不是向量並且它不是工作。

我嘗試使用 isinstance() function 檢查我感興趣的向量是否實際上是向量,但它會引發名稱錯誤。

我找不到任何關於它的建議,我確定這是因為我不明白 function 的工作原理。

這是我的代碼:

class Vector: #defined in the module Vector
 def __init__(self):
  pass

class Matrix:
 from Vector import Vector  #the module is called Vector as the class
 def __init__(self):
  pass
 def __mul__(self,other): #method called by self*other, if other is vector should perform matrix-vector multiplication
  if isinstance(other,Vector): 
   pass #I didn't write the actual content because the error arises on the condition
  pass


from Matrix import Matrix #the classes were defined in a different module
from Vector import Vector #the classes were defined in a different module

v=Vector()
A=Matrix()
A*v

錯誤消息是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Desktop\python\Matrix.py", line 82, in __mul__
    if isinstance(other,Vector):
NameError: global name 'Vector' is not defined

我在使用方法__mul__和 class 矩陣的代碼之前導入了 Vector 和 Matrix 類,我再次導入了 class 向量,因此我可以單獨使用 class 矩陣。

這些類在保存在同一目錄中的兩個不同文件中定義。

關於如何解決問題的任何提示?

看起來您已經在單獨的模塊中定義了兩個類。 沒關系(雖然在 Python 中不需要),但如果你這樣做,如果你希望它們能夠通過名稱相互引用,則需要在另一個類的模塊中import一個 class。 如果它們高度耦合在一起以至於它們需要訪問另一個,那么您可能應該將它們放在同一個模塊中。

暫無
暫無

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

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