簡體   English   中英

在 Python 中是否有與 Swift 的 keypath 功能等效的功能?

[英]Is there an equivalent to Swift's keypath feature in Python?

在 Swift 中,您可以使用稱為keypaths的語言功能來生成訪問對象屬性的函數。 例如,

// Swift

categories.map { category in category.name }

// could also be written as...

categories.map(\.name)

在 Python 中,我有時會發現自己編寫的代碼如下:

# Python
map(lambda cat: cat.name, categories)

是否有更短的方法來編寫lambda cat: cat.name ,類似於 Swift 鍵路徑?

它是operator.attrgetter

from operator import attrgetter

map(attrgetter("cat"), categories)

暫無
暫無

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

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