I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates.
My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?
In the first case, I get very low coupling, but then I will probably have to instantiate a Coord3D object with the obtained values anyway, although outside of the file class. In the second case, I will have the file class tightly coupled with the Coord3D class.
Please note that I think there's not a huge difference between the two solutions, but I would like to read your answer and the reason behind it.
Edit: to recap the answers I got until now, it looks like there's no clearcut choice. It has been said (appropriately) that python is not Java, and you don't need a specialized class for everything just because you need it by language architecture. In my case, however, I have the following conditions:
On the other hand, using a tuple has the following advantages:
further comments very welcome!
Tuples as Return Values. Functions can return tuples as return values.
That's because you can return a tuple by separating each item with a comma, as shown in the above example. “It is actually the comma which makes a tuple, not the parentheses,” the documentation points out. However, parentheses are required with empty tuples or to avoid confusion.
In each case, a function (which can only return a single value), can create a single tuple holding multiple elements. For example, we could write a function that returns both the area and the circumference of a circle of radius r.
Compromise solution: Instead of a class, make Coord3D a namedtuple
and return that :-)
Usage:
Coord3D = namedtuple('Coord3D', 'x y z')
def getCoordinate(index):
# do stuff, creating variables x, y, z
return Coord3D(x, y, z)
The return value can be used exactly as a tuple, and has the same speed and memory properties, so you don't lose any genericity. But you can also access its values by name: if c
is the result of getCoordinate(index)
, then you can work with c.x
, c.y
, etc, for increased readibility.
(obviously this is a bit less useful if your Coord3D class needs other functionality too)
[if you're not on python2.6, you can get namedtuples from the cookbook recipe]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With