Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a function with a different class as parameter

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading