问题
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