Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a class method from another file in Python?

I'm learning Python and have two files in the same directory.

printer.py

class Printer(object):
    def __init__(self):
        self.message = 'yo'

    def printMessage(self):
        print self.message

if __name__ == "__main__":
    printer = Printer()
    printer.printMessage()

How do I call the printMessage(self) method from another file, example.py in the same directory? I thought this answer was close, but it shows how to call a class method from another class within the same file.

like image 533
Thomas Avatar asked Jul 30 '17 01:07

Thomas


People also ask

How do you call a class from a different file in Python?

You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

How do you call a method from another class file?

If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method: Main m = new Main(); int a = m. getVariableName(); Hope it helps.

How do you call a class method in Python?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.


3 Answers

@Gleland's answer is correct but in case you were thinking of using one single shared instance of the Printer class for the whole project, then you need to move the instantiation of Printer out of the if clause and import the instance, not the class, i.e.:

class Printer(object):
    def __init__(self):
        self.message = 'yo'

    def printMessage(self):
        print self.message

printer = Printer()

if __name__ == "__main__":
    printer.printMessage()

Now, in the other file:

from printer import printer as pr
pr.printMessage()
like image 175
Christian K. Avatar answered Oct 18 '22 19:10

Christian K.


You have to import it and call it like this:

import printer as pr

pr.Printer().printMessage()
like image 30
Gleland Avatar answered Oct 18 '22 18:10

Gleland


In the example.py file you can write below code

from printer import Printer

prnt = Printer()

prnt.printer()

like image 30
Mayur Avatar answered Oct 18 '22 18:10

Mayur