I have a list of 9 elements. The first three represent positions, the next velocities, the next forces.
Sometimes I require forces from the array, other times velocities, and other times positions.
So I wrote a function as follows:
def Extractor(alist,quantity):
if quantity=='positions':
x = alist[0]
y = alist[1]
z = alist[2]
return (x,y,z)
elif quantity=='velocities':
vx = alist[3]
vy = alist[4]
vz = alist[5]
tot_v = np.sqrt(vx**2 + vy**2 + vz**2)
return (vx,vy,vz,tot_v)
elif quantity=='forces':
fx = alist[6]
fy = alist[7]
fz = alist[8]
tot_f = np.sqrt(fx**2 + fy**2 + fz**2)
return (fx,fy,fz,tot_f)
else:
print "Do not recognise quantity: not one of positions, velocities, force"
However, this seems like a massive code smell to me due to duplicate code. Is there a nicer, more pythonic way to do this? I'm quite new to OOP, but could I use some kind of class inheritance utilising polymorphism?
Your method violates the Single Responsibility Principle. Consider splitting it like this:
You can put them in a dictionary:
and use:
Here is an example with inheritance. It seems to be over-engineering for such a simple task though: