How to call a function from another class in python?

Yin picture Yin · May 25, 2015 · Viewed 11.7k times · Source

I'm very new to python and Sikuli software. :( I was trying to call a function from another class. Here is a class which contains the functions.

class Reader():
    def getUsername():
        ....
        return username

    def getAddress():
        .....
        return address

Here is another class which calls the functions stated above.

class DisplayInfo():
    reader = Reader()
    uName = reader.getUsername()
    addr = reader.getAddress()
    ......
    ......

But when I ran DisplayInfo class, I got this error.

uName = reader.getUsername()
TypeError: getUsername() takes no arguments (1 given)

Could anyone help me solve this? Thanks so much in advance!

Answer

Amber picture Amber · May 25, 2015

When defining Reader, the functions need to be defined to take a self argument, which is the instance of the class they were called on:

class Reader():
    def getUsername(self):
        ....
        return username

    def getAddress(self):
        .....
        return address

The error you're getting is because Python is trying to pass the class instance to the functions, but since they're defined as taking no arguments, it fails to pass that one argument.