二维数组作为对象

时间:2018-05-24 20:14:28

标签: python arrays

我问你们有没有办法创建一个二维数组作为一个类。我正在尝试完成一项任务,但我在谷歌上找不到任何关于此的研究。

如果有人知道任何有额外解释和/或解释的解决方案,请打我。

(像这样:)

class Array (object):
    def __init__ (self, row = 0, col = 0, el = 0):
       self.row = row
       self.col = col
       self.el = el

2 个答案:

答案 0 :(得分:2)

class Array(object):
    def __init__(self,row = [], col = [], el = []):
        self.row = row
        self.col = col
        self.el = el

# here testing ->

test = Array([1,2,3],[4,5,6],[7,8,9])
print(test.col)
>>> [4,5,6]

# adding to it

test.col.append[4]

#testing
print(test.col)
[4,5,6,4]

答案 1 :(得分:0)

numpy python包可以使用N-dimensional array(2D,3D,4D,... nD),但是,如果你想了解vector2D是如何创建的,这里是一个简单的例如:

class Vector2(object):
    def __init__(self, x=float(0.0), y=float(0.0)):
        self._x = x
        self._y = y
    def get_x(self):
        return self._x
    def set_x(self, value=float):
        self._x = float(value)
    x = property(get_x, set_x)
    X = property(get_x, set_x)
    def get_y(self):
        return self._y
    def set_y(self, value=float):
        self._y = float(value)
    y = property(get_y, set_y)
    Y = property(get_y, set_y)
    def __add__(self, v):
        return Vector2(self._x + v.x, self._y + v.y)
    def __radd__(self, v):
        return Vector2(v.x + self._x, v.y + self._y)
    def __sub__(self, v):
        return Vector2(self._x - v.x, self._y - v.y)
    def __rsub__(self, v):
        return Vector2(v.x - self._x, v.y - self._y)
    def __eq__(self, v):
        return self._x == v.x and self._y == v.y and self._z == v.z
    def __str__(self):
        return '(%.4f,%.4f)' % (self._x, self._y)

>>> point1 = Vector2(10, 20.1)
>>> point1.x = 50
>>> point2 = Vector2(20, 10)
>>> point1 += point2
>>> print point1 
(70.0000,30.1000)
>>> point1 == point2
False

尝试使用属性和类的内置方法(魔术方法)。 您可以在here

中阅读有关类内置方法的内容

干杯