How to Call a Class From Another Script in Python

To use a class from another Python script, save the class in a .py module, import that module or class, and create an instance such as person.Person("Alice") after import person. The important detail is that Python imports modules by filename, while classes are accessed through the imported module name or imported directly.

A class file is reusable code; it should normally define classes and functions without automatically running the application when imported.

How Python Imports Classes From Other Files

A Python module is a file containing Python definitions and statements. Its filename becomes its module name: person.py is imported as person, without the .py extension.

For a simple project, the two files can sit in the same directory:

project/
├── main.py
└── person.py

If person.py defines a Person class, main.py can import it. Python searches the current project directory and other locations on its module search path to find the module.

Imports also run a module’s top-level code the first time that module is imported in a running Python interpreter. Keep reusable definitions at the top level, and put code meant only for direct execution behind an if __name__ == "__main__": guard.

How to Import and Use a Class From Another Script

Use this method when both files are in the same project directory and you want a clear, reliable starting point.

Step 1: Put the Class in Its Own Module

  1. Create a file named person.py.
  2. Define the class at the file’s top level.
  3. Give the class methods that use self when they need data stored on each object.
# person.py
class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return f"Hello, my name is {self.name}."

The Person class is now available from the person module. Python names are case-sensitive, so Person, person, and PERSON are different names.

Step 2: Choose an Import Style

Choose the import form based on how visibly you want the source module represented in your calling code.

Import Style Import Statement Create an Object Best Use
Whole module import person person.Person("Alice") Makes the class’s source explicit and avoids name collisions
Named class from person import Person Person("Alice") Convenient when using one or two well-known definitions
Alias from person import Person as Contact Contact("Alice") Avoids a collision with another name

Choose a whole-module import when module qualification makes ownership clearer; choose a named import when one or two definitions are the API you need.

With a whole-module import, Python binds the name person, not Person, in main.py. Use the module qualifier whenever you access its class:

# main.py
import person
alice = person.Person("Alice")
print(alice.greet())

Use the imported module name and the class name defined in that file: person.Person("Alice"). The argument "Alice" is passed to Person.__init__() when the object is created.

A named import makes the class name available directly:

# main.py
from person import Person
alice = Person("Alice")
print(alice.greet())

Both forms work. The first version is often easier to read in larger projects because person.Person immediately shows where the class came from.

Step 3: Run the Calling Script

  1. Open a terminal in the directory containing main.py and person.py.
  2. Run the calling file with your Python interpreter.
  3. Check that the expected text prints without an import error.
python main.py

Expected output:

Hello, my name is Alice.

If your system uses python3 as the interpreter command, use that command instead.

Importing a Class From a Package Folder

As a project grows, place related modules in package directories instead of leaving every file in one folder.

project/
├── app/
│   ├── __init__.py
│   ├── main.py
│   └── models/
│       ├── __init__.py
│       └── person.py

The class module is now named app.models.person, not simply person. Import it using its full dotted path:

# app/main.py
from app.models.person import Person
alice = Person("Alice")
print(alice.greet())

Run the package module from the directory above app:

python -m app.main

Using -m tells Python to run app.main as part of its package. This preserves the project root in the import path and makes absolute imports predictable.

Python packages use dotted module names such as app.models.person; each directory level becomes part of the import path. The Python documentation recommends absolute imports for modules intended to act as an application’s main module because a directly executed main script does not have package context in the same way. The official Python modules documentation explains the import and package model in more detail.

Relative Imports Inside a Package

A module inside a package can use relative imports to reach a sibling or parent package module.

For example, if app/services/greeting.py needs Person from app/models/person.py:

# app/services/greeting.py
from ..models.person import Person
class GreetingService:
    def create_person_greeting(self, name):
        person = Person(name)
        return person.greet()

The two dots mean “go up one package level,” from app.services to app, then enter models.

Relative imports are useful for internal package code, but use an absolute import in the application entry point:

from app.services.greeting import GreetingService

Run package code with python -m app.main, not by directly running a nested file such as python app/main.py.

Calling a Method From Another Class

Importing a class and calling one of its methods are separate actions. Most methods need an instance because they use data stored in self.

Here is a clean pattern: one class receives an instance of another class and uses it.

# welcome_service.py
class WelcomeService:
    def __init__(self, person):
        self.person = person
    def create_message(self):
        return f"Welcome! {self.person.greet()}"

The calling script creates both objects:

# main.py
from person import Person
from welcome_service import WelcomeService
alice = Person("Alice")
welcome = WelcomeService(alice)
print(welcome.create_message())

This pattern is called composition: WelcomeService uses a Person object rather than inheriting from it or rebuilding its data. It is easier to test because you can pass a different Person instance when needed.

A method decorated with @classmethod works differently. It receives the class as cls, so it can be called from another class through the class name without making an object first:

# app_config.py
class AppConfig:
    greeting_prefix = "Hello"
    @classmethod
    def make_greeting(cls, name):
        return f"{cls.greeting_prefix}, {name}!"
# greeter.py
from app_config import AppConfig
class Greeter:
    def greet(self, name):
        return AppConfig.make_greeting(name)

Use an instance method for behavior tied to one object’s data, such as a specific person’s name. Use a class method for behavior tied to class-wide configuration or alternate constructors.

Fix Common Import Errors

Error or Symptom Likely Cause Fix
ModuleNotFoundError: No module named 'person' Python cannot find the file on its import path Run from the project root, verify the filename, or use the full package path
ImportError: cannot import name 'Person' The class name is misspelled, missing, or involved in a circular import Match capitalization and check that the class exists before importing it
AttributeError: module 'person' has no attribute 'Person' You imported a different module named person, or used the wrong class name Check person.__file__ and verify Person is defined in that file
TypeError: Person.__init__() missing ... The class constructor requires arguments you did not pass Supply the required constructor arguments when creating the object
Import works once but ignores edits in a REPL or embedded console The module is already loaded in memory Restart the interpreter while developing, or explicitly reload only when appropriate

Avoid Naming Collisions

Do not name your own files after standard-library modules or installed packages. Names such as json.py, email.py, typing.py, random.py, and requests.py can cause Python to import your local file instead of the module you expected.

To find the file Python actually imported, temporarily add this code:

import person
print(person.__file__)

The printed path should point to your project’s person.py.

I use a Python virtual environment when testing imports because it keeps installed packages from adding unrelated project-specific noise.

Avoid Circular Imports

A circular import happens when two modules need each other while Python is still initializing them.

For example, this structure is risky:

person.py          imports welcome_service.py
welcome_service.py imports person.py

The best fix is usually to move shared code into a third module or redesign the dependency so only one direction is needed. In the earlier example, main.py creates Person and passes it into WelcomeService; person.py does not need to import welcome_service.py.

Delayed imports can be useful for a deliberate advanced design, but restructuring dependencies is clearer and more reliable.

Keep Executable Code Out of Imported Modules

This code runs whenever Python imports person.py:

print("Loading person module")
class Person:
    pass

A direct-execution demo can use this pattern instead: # person.py class Person: def __init__(self, name): self.name = name if __name__ == “__main__”: demo_person = Person(“Alice”) print(demo_person.name)

# person.py
class Person:
    def __init__(self, name):
        self.name = name
if __name__ == "__main__":
    demo_person = Person("Alice")
    print(demo_person.name)

Now this command runs the demo:

python person.py

But importing person from main.py only defines the class. This makes a module safe to reuse.

Verify That the Class Import Works

A successful test checks more than whether the import statement avoids an error. It should confirm that Python loaded the expected file, constructed the object, and called a method on it.

Use this minimal main.py:

import person
print(f"Imported from: {person.__file__}")
alice = person.Person("Alice")
print(alice.greet())

Run it from the directory that contains both files:

python main.py

You should see a path ending in person.py, followed by the greeting.

For reusable code, keep imports near the top of each file, use descriptive module names, and prefer explicit imports over from module import *. Wildcard imports make it difficult to tell which module provided a class or function, and they can silently overwrite existing names.

Frequently Asked Questions

How do I call a class in Python?

Create an instance by writing the class name followed by parentheses. For a directly available class, use alice = Person("Alice"); after import person, use alice = person.Person("Alice"). The parentheses call the class constructor, usually its __init__() method.

How do I call another Python script with named parameters?

If the other file is reusable Python code, import a function or class and call it with Python keyword arguments. For example, from worker import run followed by run(name="Alice") passes name as a named argument. This is different from launching a separate script process, where values are passed as command-line arguments.

How do I import a script in Python?

Import its module name, which is usually its filename without .py. A file named tools.py is imported with import tools, while a class can be imported directly with from tools import ToolClass. Treat the file as a module when you want to reuse its definitions rather than execute it as a separate program.

Why does importing a file run some of its code?

Python executes a module’s top-level statements when it imports that module for the first time in an interpreter session. Put only definitions, constants, and safe setup at the top level. Put demos, command-line behavior, and one-time application startup inside if __name__ == "__main__":.

Should I use import module or from module import Class?

Use import module when you want calls such as module.ClassName() to show the class’s origin clearly. Use from module import ClassName when the class is central to the current file and repeating the module name adds little clarity. Avoid from module import * because it hides where names came from.