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:

  1. Import the class containing the function you want to call.
  2. Create an instance of the class.
  3. 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:

  1. Import the MyClass class from class_file.py
  2. Create an instance of the MyClas
  3. Call the my_function method using the my_instance object

Finally, this is the output of the code:
 

Hello, World!