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)]
3
  • 1
    Reassigning self is bad practice. Try having an instance variable arr and getting the elements of that through the __getitem__ magic method. Commented Oct 5, 2020 at 16:53
  • 1
    look up the python data model, specifically __getitem__ Commented Oct 5, 2020 at 16:53
  • also, reassigning self does absolutely nothing - except for having the local name self point at the list you created Commented Oct 5, 2020 at 16:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.