You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python类Foo的接口直接暴露在模块级别?

Expose Class Methods at Module Level Without Redundant Wrappers

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().fun returns a bound method—it already knows which instance to use, so you don't have to pass self manually.
  • 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 Foo for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:50:45