0

I have been assigned an exercise for my python course. The goal is to create some geometric object as subclasses of a Shape object that are going to pass some assertion evaluation.

Here is the code:

class Shape(object):
    __metaclass__ = ABCMeta
    def __init__(self, coords):
        super(Shape, self).__init__()
        self._coords = list(map(int, coords))

    def __getitem__(self, key):
        return self._coords[key]

    def move(self, distance):
        self._coords = distance

class Point(Shape):
    def __init__(self, coords):
        super(Point,self).__init__(coords)

if __name__ == '__main__':
    p = Point((0,0))
    p.move((1,1))
    assert p[0,0], p[0,1] == (1,1) # Check the coordinates

The question is how can I access a list of coords that is created in Shape super class with list indices? Is there any possibility for a list to be indexed using another list?

kotzimop
  • 3
  • 2

2 Answers2

0

If I'm understanding you correctly, you want to access an element from a list inside another list.

For that, you simply write each index in a separate pair of square brackets.

If your list is nested_list = [ [1, 2] , [3, 4] ] you access the item 4 like this:

print(nested_list[1][0])

That is equal to the long form below, which should clarify how chaining the index look-ups works:

inner_list = nested_list[1]
print(inner_list[0])
Byte Commander
  • 6,506
  • 6
  • 44
  • 71
  • it is easy for me to assert my Point instance with: p[0], p[1] == (1,1). It is True. But I have to explicitly follow the rules of the exercise. The thing is that the pair of coordinates is a list like this p._coords = [1,1]. So I don't know how to implement p[0,0] so as to have access to what it could be easily be accessed as p[0] – kotzimop May 19 '16 at 11:26
0

The exact syntax obj[m,n]==v is possible if obj is a dict!

Any hashable (most immutable) type(s) can be used as a dictionary key. Tuples, such as (1,2), are hashable. It is therefore valid to instantiate a dictionary:

>>> my_dict = { (1,2):'A', (6,7,8):'B' }

Which can be indexed:

>>> my_dict[1,2]
'A'
>>> my_dict[6,7,8]
'B'
>>> assert my_dict[6,7,8] == 'B'

This approach would allow you to match the assertion syntax.

A. Vidor
  • 2,502
  • 1
  • 16
  • 24