Last modified: Jun 27, 2023 By Alexander Williams
Python: Call Function In Class From Another File
To call a function in a class from another file in Python, follow these steps:
- Import the class containing the function you want to call.
- Create an instance of the class.
- Call the function using the instance.
Great, now let's say we have a file called class_file.py
that contains the class and function you want to call:
class MyClass:
def my_function(self):
print("Hello, World!")
Now, in another file, let's call it main.py
, you want to call the my_function
from class_file.py
:
from class_file import MyClass
# Create an instance of MyClass
my_instance = MyClass()
# Call the function using the instance
my_instance.my_function()
When you run main.py
it will:
- Import the
MyClass
class fromclass_file.py
- Create an instance of the
MyClas
- Call the
my_function
method using themy_instance
object
Finally, this is the output of the code:
Hello, World!