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.
You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method: Main m = new Main(); int a = m. getVariableName(); Hope it helps.
To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.
@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()
You have to import it and call it like this:
import printer as pr
pr.Printer().printMessage()
In the example.py file you can write below code
from printer import Printer
prnt = Printer()
prnt.printer()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With