Skip to main content
 首页 » 编程设计

python之创建一个新的范围,如 javascript

2025年05月04日52itcoder

看完Lisp in Your Language ,我一直在尝试在 Python 中跟进。一切正常,直到我到达 variable assignment and scoping .

最后的电话让我难住了。似乎在 javascript 中,可以创建一个新的范围对象并将对象分配或绑定(bind)到该新范围,而不是使用“this”。在示例链接中:

// use existing local scope or create a new one 
scope = scope || {}; 
 
[...] 
 
// call the function with these arguments 
// and expose scope as this 
return fn.apply(scope, args); 

在 Python 中,这似乎不可能以同样的方式进行。在此之前我一直在调用 return fn(*args),但现在我对如何编写等效代码感到困惑。

有什么想法或建议吗?

Gist of my updated code

编辑:我已经找到了这个问题的解决方案,至少现在是这样:

# defined outside of the function 
global scope_dict 
scope_dict = {} 
 
def pl_def(name, value): 
    global scope_dict 
    scope_dict[name] = value 
    return scope_dict[name] 
 
[...] 
 
# use existing scope inside the function 
global scope_dict 
scope = scope_dict 
 
# resolve all our new string names from our scope 
def symbol_check(symbol): 
    if isinstance(symbol, list): 
        return symbol 
    elif symbol in scope: 
        return scope[symbol] 
    else: 
        return symbol 
expression = [symbol_check(x) for x in rawExpr] 
 
[...] 
 
# call the function with these arguments 
return fn(*args) 

请您参考如下方法:

在您链接到的页面的代码中,scope 只是一个对象——它没有什么特别之处。但是在 JS 中,您可以使用括号表示法和点表示法访问对象的属性:

//these are equivalent 
obj.prop 
obj['prop'] 

在 Python 中,要获取“常规”对象的属性,您必须使用点符号或 getattr()。

由于示例中的 scope 对象只是被视为一个容器,您可以使用 dict 代替,然后代码可能会在没有太多其他修改的情况下工作.巧合的是,{} 在 JS 中创建了一个空对象,但在 Python 中创建了一个空的 dict。