So, this is probably a really simple question but I just cant figure it out:
I have 1 function that, when called, uses the variables from a class to return either a True or False:
def adjacente(dist):
return(
abs(totalmov.xi - totalmov.xf) == dist and abs(totalmov.yi - totalmov.yf) <= dist or
abs(totalmov.yi - totalmov.yf) == dist and abs(totalmov.xi - totalmov.xf) <= dist)
But the thing is, I want to be able to execute this function without having it hardcoded to the class "totalmov", for instance, I want to be able to execute the same very function with the class "movimento" and the only way I have thought so far was to create the same very function but with a different name:
def adjacente_2(dist):
return(
abs(movimento.xi - movimento.xf) == dist and abs(movimento.yi - movimento.yf) <= dist or
abs(movimento.yi - movimento.yf) == dist and abs(movimento.xi - movimento.xf) <= dist)
There 100% must be a way to do the same thing but without repeating functions, can someone tell me how? Thank you
CodePudding user response:
All you have to do is add another parameter to your function definition (called something sensible; here, I've called it movement
), and then use that in place of the class names inside your function body:
def adjacente(dist, movement):
return(
abs(movement.xi - movement.xf) == dist and abs(movement.yi - movement.yf) <= dist or
abs(movement.yi - movement.yf) == dist and abs(movement.xi - movement.xf) <= dist)
So long as whatever you pass as a function argument has attributes of appropriate types called xi
, yi
, xf
, and yf
, this will work.