如何将Python类Foo的接口直接暴露在模块级别?
If you want to make your Foo class's methods directly callable from the module level (instead of forcing users to instantiate Foo or writing those clunky redundant wrapper functions), here's a clean, Pythonic solution:
Step 1: Keep Your Class Definition
First, maintain your Foo class as is in foo.py:
class Foo(): def fun(self): print("Running Foo's fun method!")
Step 2: Avoid Redundant Wrappers
Skip the unnecessary wrapper function that just delegates to an instance:
# ❌ This is the redundant pattern we want to eliminate def fun(): return Foo().fun()
Step 3: Bind the Instance Method to a Module Variable
Instead, create an instance of Foo and bind its method directly to a module-level name. This gives you a bound method that automatically uses the instance when called:
# ✅ Clean solution: Bind the method to a module variable fun = Foo().fun
If you need to reference the instance elsewhere in the module, you can also split it into two lines for clarity:
foo_instance = Foo() fun = foo_instance.fun
How to Use the Module
Now users can import your module and call the method directly, no extra instantiation required:
import foo foo.fun() # Outputs: Running Foo's fun method!
Quick Notes
- This works because
Foo().funreturns a bound method—it already knows which instance to use, so you don't have to passselfmanually. - For multiple methods, repeat the pattern for each one you want to expose:
class Foo(): def fun(self): pass def helper(self): pass foo_instance = Foo() fun = foo_instance.fun helper = foo_instance.helper - This uses a single shared instance of
Foofor all module-level calls. If you need a fresh instance every time the method runs, this approach isn't ideal—but that's rarely the goal when exposing methods at the module level.
内容的提问来源于stack exchange,提问作者bartosz

