【发布时间】:2019-07-14 01:44:23
【问题描述】:
在 Javascript 中,我可以使用 destructuring 从一个 javascript 对象中提取我想要的属性。例如:
currentUser = {
"id": 24,
"name": "John Doe",
"website": "http://mywebsite.com",
"description": "I am an actor",
"email": "example@example.com",
"gender": "M",
"phone_number": "+12345678",
"username": "johndoe",
"birth_date": "1991-02-23",
"followers": 46263,
"following": 345,
"like": 204,
"comments": 9
}
let { id, username } = this.currentUser;
console.log(id) // 24
console.log(username) //johndoe
对于 Python 字典和 Python 对象,我们在 Python 中有类似的东西吗? Python对象的Python方式示例:
class User:
def __init__(self, id, name, website, description, email, gender, phone_number, username):
self.id = id
self.name = name
self.website = website
self.description = description
self.email = email
self.gender = gender
self.phone_number = phone_number
self.username = username
current_user = User(24, "Jon Doe", "http://mywebsite.com", "I am an actor", "example@example.com", "M", "+12345678", "johndoe")
# This is a pain
id = current_user.id
email = current_user.email
gender = current_user.gender
username = current_user.username
print(id, email, gender, username)
写这 4 行(如上例所述)与写一行(如下所述)从对象中获取我需要的值是一个真正的痛点。
(id, email, gender, username) = current_user
【问题讨论】:
-
print(currentUser['id'])在 Python 中? -
#e.dan 这个问题更广泛 - 涵盖 dict 和 objects。
-
关于您的第二个问题 (
User),请参阅 attrs 库:attrs.org/en/stable。或者有这种方法:self.__dict__.update(locals()) -
为什么你首先需要那些“痛苦”的台词?您不能只访问对象中的值吗?
标签: python