How do I call a class method from another file in Python?
In the example.py file you can write below code
from printer import Printer
prnt = Printer()
prnt.printer()
@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()
You have to import it and call it like this:
import printer as pr
pr.Printer().printMessage()