Python .run()

THE-Spellchecker's avatar
Published Jun 3, 2022Updated May 15, 2024
Contribute to Docs

The .run() method executes any target function belonging to a given thread object that is now active. It normally executes in the background after the .start() method is invoked.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

thread_object.start()
# .run() executing in the background

The .run() method commonly takes the form of the target function passed to the thread_object, if any.

Example

The .run() method can be overridden with different instructions and statements in a separate subclass, like in the example below:

import threading
class CustomThread(threading.Thread):
def run(self):
print("This is my custom run!")
custom_thread = CustomThread()
custom_thread.start()

After the .start() method is called against the custom_thread, the overridden .run() method is executed and the following is printed:

This is my custom run!

Codebyte Example

Choosing whether or not to override the .run() method is a matter of preference. It exists to assist Java developers with learning to use threads in Python. Passing a target function into the .Thread() constructor and then invoking the .start() will achieve the same thing:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours