簡體   English   中英

Python 是否支持 object 文字屬性值簡寫,如 ECMAScript 6?

[英]Does Python support object literal property value shorthand, a la ECMAScript 6?

在 ECMAScript 6 中,我可以做這樣的事情......

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { id, name, email };

...作為這個的簡寫:

var id = 1;
var name = 'John Doe';
var email = 'email@example.com';
var record = { 'id': id, 'name': name, 'email': email };

Python有沒有類似的功能?

不,但是您可以做到這一點

record = {i: locals()[i] for i in ('id', 'name', 'email')}

(將Python變量的信用作為dict的鍵

但我不會這樣做,因為它會損害可讀性,並使靜態檢查器無法找到未定義名稱的錯誤。

您直接在python中輸入的示例與set相同,不是字典

{id, name, email} == set((id, name, email))

由於設置了文字,您不能輕易使用對象文字的簡寫,而locals()有點不安全。

幾年前,我寫了一個hacky gist ,它創建了一個可以使用的d函數,例如

record = d(id, name, email, other=stuff)

去看看我是否可以包裝得更好。

不,Python中沒有類似的速記。 它甚至會引入帶有set字面量的歧義,這些字面量具有確切的語法:

>>> foo = 'foo'
>>> bar = 'bar'
>>> {foo, bar}
set(['foo', 'bar'])
>>> {'foo': foo, 'bar': bar}
{'foo': 'foo', 'bar': 'bar'}

是的,你可以使用一個名為sorcery的黑魔法庫來很好地實現這一點,它提供了dict_of

x = dict_of(foo, bar)
# same as:
y = {"foo": foo, "bar": bar}

注意,你也可以像 ES6 一樣解壓:

foo, bar = unpack_keys(x)
# same as:
foo = x['foo']
bar = x['bar']

這可能會讓有經驗的 Python 愛好者感到困惑,並且對於性能敏感的代碼路徑來說可能不是一個明智的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM