Py学习  »  Python

用python解构dict和objects

Lokesh Agrawal • 5 年前 • 2133 次点击  

在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 dict和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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40848
 
2133 次点击  
文章 [ 2 ]  |  最新文章 5 年前