【问题标题】:REPL - recover callable after redefining itREPL - 重新定义后恢复可调用
【发布时间】:2015-09-05 22:05:47
【问题描述】:

我在 Python REPL 中做了一些工作,并重新定义了一个原始可调用对象。

list = [] 将阻止tuple = list((1,2,3)) 继续工作。

除了重新启动 REPL 之外,还有没有办法“恢复”或将列表重新分配为其默认值?

也许有导入或超类?或者它会永远丢失并坚持我分配的内容,直到我重新启动 REPL?

【问题讨论】:

    标签: python read-eval-print-loop


    【解决方案1】:

    您可以删除名称del list

    In [9]: list = []    
    In [10]: list()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-10-8b11f83c3293> in <module>()
    ----> 1 list()
    
    TypeError: 'list' object is not callable    
    In [11]: del list    
    In [12]: list()
    Out[12]: []
    

    或者list = builtins.list 用于python3:

    In [10]: import builtins
    In [11]: list = []    
    In [12]: list()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-12-8b11f83c3293> in <module>()
    ----> 1 list()
    
    TypeError: 'list' object is not callable    
    In [13]: list = builtins.list    
    In [14]: list()
    Out[14]: []
    

    对于python 2:

    In [1]: import __builtin__    
    In [2]: list = []    
    In [3]: list()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-3-8b11f83c3293> in <module>()
    ----> 1 list()    
    TypeError: 'list' object is not callable  
    In [4]: list = __builtin__.list  
    In [5]: list()
    Out[5]: []
    

    【讨论】:

    • 谢谢,这行得通!是否还有其他方法也可能有效,或者仅此一种?
    • 有 (list = __builtins__.list, list = type([])) 但 Padraic 的方法更好,因为其他方法只是通过与内置函数相同的本地名称隐藏内置函数;他的解决方案消除了阴影。
    • @MarkN,是的,添加了一种使用 builtin.list 的方法,但我同意 ^^
    • __builtins__,恰好引用了一个名为__builtin__的模块。这很混乱。
    • @MarkN,是的,按照 Remo 的建议使用 __builtins__
    猜你喜欢
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多