如何修复 AttributeError:“Matrix”对象没有“clear”属性?

我正在尝试创建一个 Matrix 类。但是,当我创建它时它会给我带来错误。


我试图删除 self._theGrid.clear(0) 但矩阵将被初始化为 None 而不是 0。


from array_ import Array2D


class Matrix :

    # Creates a matrix of size numRows x numClos initialized to 0.

    def __init__(self, numRows, numCols):

        self._theGrid = Array2D(numRows, numCols)

        self._theGrid.clear(0)

    ....

在我创建的模块中。我正在使用以下模块来创建矩阵。



# Implement the Array ADT using the array capabilities of the ctypes module

import ctypes


class Array:

     # Create array with the size elements

    def __init__(self, size):

        assert size > 0, "Array size must be > 0"

        self._size = size

         # Create the array structure using ctypes module

        PyArrayType = ctypes.py_object * size

        self._elements = PyArrayType()

         # Initialize each element

        self.clear(None)


     # Returns the size of the array

    def __len__(self):

        return self._size


     # Get the contents of the index element

    def __getitem__(self, index):

        assert index >= 0 and index < len(self), "Array subscripts out of range"

        return self._elements[index]


      # Puts the value in the array element at index position.

    def __setitem__(self, index, value):

        assert index >= 0 and index < len(self), "Array subscripts out of range"

        self._elements[index] = value


     # Clear the array by setting each element to the given value.

    def clear (self, value):

        for i in range(len(self)):

            self._elements[i] = value

     # Returns the array's ierator for transversing the elements.

    def __iter__(self):

        return _ArrayIterator( self._elements )

# An iterator for the Array ADT.

class _ArrayIterator:


    def __init__(self, theArray):

        self._arrayRef = theArray

        self._curNdx = 0


    def __iter__(self):

        return self


我无法得到所有矩阵条目都初始化为 0 的结果。


第 8 行,在init self._theGrid.clear(0)


第 77 行,在 clear row.clear(value) 中


AttributeError:“矩阵”对象没有属性“清除”


我无法用 x = Matrix(2,3) 初始化矩阵。


慕勒3428872
浏览 90回答 1
1回答

呼唤远方

您似乎在这里迭代数组的长度:...def clear( self, value ):&nbsp; &nbsp; for row in range( self.numRows() ):&nbsp; # row is 0, 1, 2, ...&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; row.clear( value )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# int has no method or attribute with name "clear" -> error is raised...尝试遍历数组:...def clear( self, value ):&nbsp; &nbsp; for row in self._theRows:&nbsp; &nbsp; &nbsp; &nbsp; row.clear( value )&nbsp;...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python