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

Python中如何实现类似time.stop()的层级函数调用?

实现Python层级函数调用的几种方法

你想实现的example.example2()这种层级调用,本质是在一个命名空间下嵌套另一个命名空间再挂载函数。直接写def example.example是语法错误,因为函数名不能包含.,下面给你两种简单可行的实现方式,都能在单个文件里完成:

方法一:用类作为命名空间

这是最容易上手的方式,把嵌套层级做成类,里面的方法用@staticmethod装饰,不需要实例化就能直接调用:

# 比如你的文件叫my_utils.py
class example:
    @staticmethod
    def example2():
        print("这是example2的执行逻辑")
    
    @staticmethod
    def delay(seconds):
        import time
        time.sleep(seconds)
        print(f"等待了{seconds}秒")

# 还可以加其他层级
class tools:
    @staticmethod
    def format_text(text):
        return text.strip().upper()

使用的时候直接导入:

# 方式1:导入整个模块
import my_utils
my_utils.example.example2()
my_utils.example.delay(1)
my_utils.tools.format_text("  hello  ")

# 方式2:直接导入层级
from my_utils import example
example.delay(1)

方法二:用模块对象模拟嵌套模块

如果想更贴近time.sleep()这种原生模块的层级感,可以用types.ModuleType创建子模块对象,把函数挂载上去:

# my_utils.py
import types

# 创建子模块对象
example = types.ModuleType("example")

# 定义函数
def example2():
    print("这是example2的执行逻辑")

def delay(seconds):
    import time
    time.sleep(seconds)
    print(f"等待了{seconds}秒")

# 把函数绑定到子模块
example.example2 = example2
example.delay = delay

# 新增其他子模块
tools = types.ModuleType("tools")
def format_text(text):
    return text.strip().upper()
tools.format_text = format_text

使用方式和方法一完全一样,这种方式的好处是example在类型上就是模块,和Python原生的模块层级逻辑一致。

为什么之前的写法不行?

Python里def后面必须跟合法的标识符(不能包含.、空格这些特殊字符),所以def example.example是违反语法规则的,必须通过命名空间嵌套的方式实现层级调用。

内容的提问来源于stack exchange,提问作者Ruben Sutton

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:42:15