Thomas
Thomas

Reputation: 6188

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.

Upvotes: 14

Views: 45247

Answers (3)

Mayur
Mayur

Reputation: 21

In the example.py file you can write below code

from printer import Printer

prnt = Printer()

prnt.printer()

Upvotes: 1

Christian K.
Christian K.

Reputation: 2823

@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()

Upvotes: 6

Gleland
Gleland

Reputation: 260

You have to import it and call it like this:

import printer as pr

pr.Printer().printMessage()

Upvotes: 9

Related Questions