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

北慕城南 提交于 2020-01-03 15:49:48

问题


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.


回答1:


You have to import it and call it like this:

import printer as pr

pr.Printer().printMessage()



回答2:


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


来源:https://stackoverflow.com/questions/45395630/how-do-i-call-a-class-method-from-another-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!