Python script with Class and object

i want to run a python script with a class and methods
most of the examples i see have a python script with a simile function returning some value without wrapped inside a class and methods.
I could build UIPath program to call a python with simple function to return a string value.
i couldn’t invoke a method in the class.
is there any example for this case. any specific steps i can follow…

Thanks,

1 Like

Hi @Gowtham_M,

Can you give a more concrete example of what you are trying to run?
I’ll see if I can find some steps in the mean time.

Do you want to use the Get Python Object / Invoke Python Method activities? Or simply Run Python Script activity?

So I did a bit more research on how to use the Python Invoke / Get Object etc and there are some limitations.

This is the python script I used:

class Person:
    def __init__(self, name, age, location):
        self.name = name
        self.age = age
        self.location = location

    def change_name(self, new_name):
        self.name = new_name

    def change_location(self, new_location):
        self.location = new_location

    def print_location(self):
        print(self.location)
        return self.location


sergiu = Person(name="Sergiu", age="69", location="everywhere")


def get_location_for_sergiu():
    return sergiu.print_location()

I couldn’t manage to have the import of the class from another file. For some reason it said it couldn’t find the other files, even though they were in the same folder.

Basically you have to have a return in the class of the value you want, and then have a method outside of the class, in the base of the script that calls the class method with a return. It’s a bit weird, totally not respecting PEP8 / Zen of Python.

As for the studio code the process is as follows:

I tried to name the variables to be pretty self explanatory.
The “Load Python Script” activity loads your python script, saved in pyScript, and returns an instance of the script in pyInstance.
The “Invoke Python Method” activity loads the instance, you specify the name (and parameters) of the function you want and save the result in pyObject.
The “Get Python Object” activity takes the pyObject and gives you what you want from it by selecting the correct output type. String in our case, saved in location.

Finally I’ve written that to the console output for testing purposes.

Hope this helps/answers your question, if not let me know and I’ll see if I can be of more help :slight_smile:

3 Likes

Thanks Sergiu, This helps.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.