所以我定義了以下要輸入到類中的函式:
MatrixConverter(arr)
它完全按照我的意愿作業,將一個 numpy 陣列作為引數,并生成一個更簡單的矩陣作為一個 numpy 陣列。
現在,我想定義一個由 numpy 陣列初始化的類,一旦我將一個矩陣輸入到類中,稱為 ManyConvertor,就可以通過 運行輸入的矩陣MatrixConverter,從而創建轉換后矩陣的內部表示。我的嘗試如下:
class SeveralConvertor:
def __init_(self,matrix)
self.matrix=np.array(matrix)
def MatrixConverter(self)
假設q是一些隨機陣列,然后鍵入q.MatrixConverter會出現以下錯誤:
<bound method SeveralConverter.MatrixConverter of <__main__.SeveralConverter object at 0x7f8dab038c10>>
現在,正如我所說,該函式MatrixConverter(arr)作為一個函式可以正常作業,但是當我將它輸入到類中時,我將所有的交換arr為self,這可能與問題有關。
幫助將不勝感激!
uj5u.com熱心網友回復:
不需要做任何太花哨的事情,我們可以將(單元測驗的)函式系結到類方法,然后在__init__函式中呼叫它。
def matrixConverter(arr):
# Some complicated function you already wrote
raise NotImplementedError
class SeveralConverter:
def __init__(self, matrix):
self.matrix = self._MatrixConverter(matrix)
@staticmethod
def _MatrixConverter(arr):
""" Call the Matrix Converter Function """
return MatrixConverter(arr)
然后在您的代碼中(將上面的內容放在一個模塊中并匯入該類)
matrix_converted = SeveralConverter(ugly_matrix)
print(matrix_converted.matrix) # Prints the converted matrix
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473551.html
上一篇:用大寫反轉每個單詞而不更改單詞
