How to Call a Function Outside a Class in Python

Python is an object-oriented programming language that enables developers to structure software around objects, data, and classes. In this context, classes can be defined as abstract data types that encapsulate functions and data into one entity.

Sometimes it’s necessary to call a function from outside a class. In this tutorial, we will be looking closely at how to call a function outside a class in Python.

Step 1: Define a Simple Python Function

First, we will define a simple Python function. A function is a reusable piece of code that performs a specific task. To define a function in Python, we use the “def” keyword, followed by the name of the function and a colon. Here’s an example of a simple function that prints a greeting.

Step 2: Define a Class

Next, let’s define a Python class. A class is a template for creating objects in Python. To define a class, we use the “class” keyword, followed by the name of the class and a colon. Here’s an example of a simple class with a single method that calls our greeting function.

Step 3: Call the Function Outside the Class

Finally, to call the function outside the class, we first create an instance of the class, and then call the class method that internally calls our function:

When we run this Python script, we will see the output “Hello, world!”, which is generated by our greeting function that was called outside the class.

Full Example Code

Here is the complete Python script for calling a function outside a class:

Output:

Hello, world!

Conclusion

Understanding object-oriented concepts such as classes and functions is an important part of Python development.

While functions are often defined and used within classes, they can also be defined separately and called from outside a class. This approach can provide more flexibility in how you structure and reuse your code.