【问题标题】:Subclassing __dir__ on a Python module在 Python 模块上子类化 __dir__
【发布时间】:2021-05-09 08:33:48
【问题描述】:

从 Python 3.7 开始,可以在模块上定义 __dir__()。但是,如果您想获取 dir(module) 的“正常”输出并从中添加或删除呢?

例如,我想做这样的事情:

def __dir__():
    dir_out = super().__dir__()[:]  # does not work
    dir_out.pop('Optional')  # get rid of the typing imports
    return dir_out

显然因为模块不是普通类,super() 调用不起作用。但是还有其他方法吗?

【问题讨论】:

    标签: python-3.x super python-class


    【解决方案1】:

    使用globals() 命令获取通常会出现在目录中的内容:

    def __dir__():
        dir_out = list(globals()) 
        dir_out.pop('Optional')  # get rid of the typing imports
        return dir_out
    

    【讨论】:

    猜你喜欢
    • 2010-10-20
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-24
    • 2021-04-19
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多