我正在嘗試創建一個表示向量(稱為 Vector)的類和一個表示矩陣(稱為 Matrix)的類。定義矩陣向量乘積時出現的問題:我在實際實作中看不到錯誤,但我嘗試在代碼之前添加一個檢查以引發錯誤,如果第二個元素不是向量并且它不是作業。
我嘗試使用 isinstance() 函式來檢查我感興趣的向量是否實際上是向量,但它會引發名稱錯誤。
我找不到任何關于它的建議,我確定這是因為我不了解該功能的作業原理。
這是我的代碼:
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
在使用該方法之前,我同時匯入了 Vector 和 Matrix 類,__mul__
并且在 Matrix 類的代碼中我再次匯入了 Vector 類,因此我可以單獨使用 Matrix 類。
這些類在保存在同一目錄中的兩個不同檔案中定義。
關于如何解決問題的任何提示?
uj5u.com熱心網友回復:
看起來您已經在單獨的模塊中定義了兩個類。沒關系(盡管在 Python 中不需要),但如果你這樣做,import
如果你希望它們能夠通過名稱相互參考,則需要另一個類的模塊中的一個類。如果它們高度耦合在一起以至于它們都需要訪問另一個,那么您可能應該將它們放在同一個模塊中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507292.html