1

I am writing a code to return the coordinates of a point in a list of points. The list of points class is defined as follows:

class Streamline:

## Constructor
#  @param ID     Streamline ID
#  @param Points list of points in a streamline
def __init__ ( self, ID, points):
    self.__ID           = ID
    self.__points        = points

## Get all Point coordinates
#  @return Matrix of Point coordinates
def get_point_coordinates ( self ):
    return np.array([point.get_coordinate() for point in self.__points])

With

class Point:
## Constructor
#  @param ID     Streamline ID
#  @param cor    List of Coordinates
#  @param vel    List of velocity vectors (2D)
def __init__ ( self, ID,  coord, veloc):
    self.__ID           = ID
    self.set_coordinate( coord )
    self.set_velocity( veloc )

The thing is that I start my code by defining a Streamline with one Point in the point list. A little down the road I call the function get_point_coordinates and the iteration over the list of points raises the following error:

return np.array([point.get_coordinate() for point in self.__points])
TypeError: iteration over non-sequence

I need to find a way to bypass this error and neatly return just a 1x2 matrix with the point coordinates.

I've had a look at this question but it wasn't very helpful.

Community
  • 1
  • 1
Henk12
  • 13
  • 2

1 Answers1

0
  1. Either call the Streamline-constructor with a sequence instead of a single point: sl = Streamline(ID, [first_point])

  2. Or ensure the constructor makes the single point to be iterable:

    class Streamline:
        def __init__ ( self, ID, first_point):
            self.__ID     = ID
            self.__points = [first_point]
    
  3. It is a bad idea to write the constructor to accept a single point (Streamline(ID, point1)) and a sequence of points (Streamline(ID, [point1, point2, ...])). If you want so, you can do

    from collections import Iterable
    class Streamline:
        def __init__ ( self, ID, first_point):
            self.__ID     = ID
            self.__points = points if isinstance(points, Iterable) else [points]
    
  4. Better than 3. would be to unpack the points given in arguments via * to enable Streamline(ID, point1) and Streamline(ID, point1, point2, ...).

    class Streamline:
        def __init__ ( self, ID, *points):
            self.__ID     = ID
            self.__points = points
    
Chickenmarkus
  • 1,131
  • 11
  • 25