【问题标题】:Creating a new scope like javascript创建一个新的范围,如 javascript
【发布时间】:2015-12-07 00:34:51
【问题描述】:

在阅读Lisp in Your Language 之后,我一直在尝试使用 Python。一切正常,直到我到达variable assignment and scoping

最后的电话把我难住了。似乎在 javascript 中,可以创建一个新的范围对象并将对象分配或绑定到该新范围,而不是使用“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)

【问题讨论】:

  • 最简单的方法是运行函数,它们有自己的本地命名空间。如果您明确要创建范围,可以使用exec()

标签: python python-3.x scope


【解决方案1】:

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

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

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

由于示例中的scope 对象只是被视为一个容器,因此您可以使用dict 来代替,这样代码就可以在没有太多其他修改的情况下运行。巧合的是,{} 在 JS 中创建了一个空对象,但在 Python 中创建了一个空 dict

【讨论】:

  • 谢谢!您关于使用dict 的评论为我指明了正确的方向。我已经用我的解决方案编辑了问题。
【解决方案2】:

您不能在 python 中 100% 复制它,因为函数对象没有像在 javascript 中那样定义 this(python 中为 self)。

$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
>>> def no_scope():
...   print(self)
...
>>> no_scope()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in no_scope
NameError: name 'self' is not defined

通过节点在javascript中

$ node
> function scope() {
... console.log(this);
... }
undefined
> scope()
{ DTRACE_NET_SERVER_CONNECTION: [Function],
  DTRACE_NET_STREAM_END: [Function],
  DTRACE_NET_SOCKET_READ: [Function],
  DTRACE_NET_SOCKET_WRITE: [Function],
  // ... etc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多