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

Thomas picture Thomas · Jul 30, 2017 · Viewed 19.4k times · Source

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.

Answer

Gleland picture Gleland · Jul 30, 2017

You have to import it and call it like this:

import printer as pr

pr.Printer().printMessage()