Search code examples
pythonmember-functions

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.


Solution

  • You have to import it and call it like this:

    import printer as pr
    
    pr.Printer().printMessage()