[英]How do I define an array class in Python?
I want to define a point, then define an array of three points as a class.我想定义一个点,然后定义一个由三个点组成的数组作为一个类。 Given the definition below, I can do this and it works:
鉴于下面的定义,我可以做到这一点,它的工作原理:
a = [POINT(0,0) for i in range(4)]
but I want to be able to do this:但我希望能够做到这一点:
a = THREEPOINTS()
and then do this:然后这样做:
a[2].x = 7
a[2].y = 3
My attempt is below but it doesn't work.我的尝试如下,但不起作用。 Is there a way to define a class that is an array?
有没有办法定义一个数组类?
class POINT:
def __init__(self, x, y):
self.x = x
self.y = y
class THREEPOINTS:
def __init__(self):
self = [POINT(0,0) for i in range(4)]
THREEPOINTS
itself is not a list; THREEPOINTS
本身不是一个列表; it will have a list-valued attribute.它将具有列表值属性。
class THREEPOINTS:
def __init__(self):
self.points = [POINT(0,0) for i in range(3)]
def __getitem__(self, i):
return self.points[i]
def __setitem__(self, i, v):
self.points[i] = v
Note the use of range(3)
, not range(4)
, to define 3 points.注意使用
range(3)
而不是range(4)
来定义 3 个点。 If you want your THREEPOINTS
indexed from 1 to 3 rather than 0 to 2, you can subtract one from i
in __getitem__
and __setitem__
to map your 1-based indices to 0-based indices used by the list.如果您希望将
THREEPOINTS
索引为从 1 到 3 而不是 0 到 2,则可以从__getitem__
和__setitem__
i
中减去 1,以将基于 1 的索引映射到列表使用的基于 0 的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.