Python 中的 ES6 计算属性名称

qar*_*dso 1 python syntax dictionary

我正在尝试在 Python 中找到等效的 ES6 功能。

在JS中,我有这样的事情:

let obj = {['composed' + objKey()]: true}
Run Code Online (Sandbox Code Playgroud)

我也希望能够在 Python 的 dict 构造函数中编写字典键,例如:

MyClass.render(storyboard=dict([getAuthor()]=self.authorStoryData()))
Run Code Online (Sandbox Code Playgroud)

[getAuthor()]应该导致该函数返回值的字典键。或者如果它是可变的,它的价值,等等......

有没有办法在 Python 中做到这一点?

我试过这样做,dict=('%s' % (variable,)=self.content但这引发了错误。

pok*_*oke 6

就像您在 JavaScript 中使用对象字面量一样,为此您应该在 Python 中使用字典字面量。这将是 Python 中的完全等价物:

def objKey():
   return 'foo'

obj = {
    'composed' + objKey(): True
}

print(obj['composedfoo']) # True
Run Code Online (Sandbox Code Playgroud)

或者在您的实际情况中:

MyClass.render(storyboard={ getAuthor(): self.authorStoryData() })
Run Code Online (Sandbox Code Playgroud)

正如 Jon 在评论中强调的那样,JavaScript 对象字面量和 Python dict 字面量之间的最大区别在于 Python 对键的行为基本上[]是默认情况下JavaScript 的行为。

因此,要{ [expr]: value }在 JavaScript 中翻译 a ,您将{ expr: value }使用 Python编写。但是当你只用{ key: value }JavaScript编写时,你必须理解它本质上是一个{ ['key']: value }使得它等同{ 'key': value }于 Python 的。

The reason why you need a string literal for string keys is simply because Python dictionaries can have almost arbitrary key objects and are not limited to string keys as JavaScript objects are.

  • 基本上没有`[]`语法的任何你想要的。虽然 `something` 将在 Python 中的 JS 中成为一个文字,但它将是 `something` 的 *value* ......并且您必须使文字显式用于文字...... (2认同)