0

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)]
Craicerjack
  • 6,203
  • 2
  • 31
  • 39
  • 1
    Reassigning `self` is bad practice. Try having an instance variable `arr` and getting the elements of that through the [`__getitem__`](https://stackoverflow.com/questions/43627405/understanding-getitem-method) magic method. – rassar Oct 05 '20 at 16:53
  • 1
    look up the [python data model](https://docs.python.org/3/reference/datamodel.html), specifically `__getitem__` – acushner Oct 05 '20 at 16:53
  • also, reassigning `self` does absolutely nothing - except for having the local name `self` point at the list you created – acushner Oct 05 '20 at 16:53

1 Answers1

4

THREEPOINTS itself is not a list; 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. 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.

chepner
  • 497,756
  • 71
  • 530
  • 681