[英]Class object has no attribute 'get'
I am trying to order a list user data, in the form of dictionaries, which contains random user data generated by an API.我正在尝试以字典的形式订购一个列表用户数据,其中包含由 API 生成的随机用户数据。 I am using .get to pull the date of birth (dob) from the dictionaries within the list to organize the data, but I keep getting the error "AttributeError: 'randomuser' object has no attribute 'get'".
我正在使用 .get 从列表中的字典中提取出生日期 (dob) 以组织数据,但我不断收到错误“AttributeError: 'randomuser' object has no attribute 'get'”。 Since it seems that the problem is coming from the interaction with the 'randomuser' class, I tried side-stepping the class by placing the user data directing into a user dictionary in the main program loop, and this seemed to work.
由于问题似乎来自与 'randomuser' 类的交互,我尝试通过将用户数据定向放入主程序循环中的用户字典来绕过该类,这似乎有效。 But as I am trying to learn OOP, any help in explaining where I am going wrong with the 'randomuser' class is appreciated!
但是当我尝试学习 OOP 时,任何帮助解释我在 'randomuser' 类中出错的地方都表示赞赏! Cheers!
干杯!
import requests
import json
class randomuser(object):
def __init__(self, firstname, lastname, gender, username, password, dob) -> None:
self.firstname = firstname
self.lastname = lastname
self.gender = gender
self.username = username
self.password = password
self.dob = dob
self.user_dict = {
"firstname": self.firstname,
"lastname": self.lastname,
"gender": self.gender,
"username": self.username,
"password": self.password,
"dob": self.dob
}
def __repr__(self):
return str(self.user_dict)
"""
create a 10 user list with 5 men and 5 women
"""
male = 0
female = 0
user_list = []
while male < 5 or female < 5:
response = requests.get("https://randomuser.me/api/") # pulls JSON object from API
user = json.loads(response.text)['results'][0] # converst to Python dictionary
firstname = user['name']["first"]
lastname = user['name']["last"]
gender = user['gender']
username = user['login']['username']
password = user['login']['password']
dob = user['dob']['date']
new_user = randomuser(firstname, lastname, gender, username, password, dob)
if gender == 'male' and male < 5:
male += 1
user_list.append(new_user)
elif gender == 'female' and female < 5:
female += 1
user_list.append(new_user)
"""
sort user list by DOB
"""
user_list.sort(key=lambda x: x.get('dob'))
print(user_list)
You have a list of classes, not dictionaries, so your lambda argument is a class without a get
function你有一个类列表,而不是字典,所以你的 lambda 参数是一个没有
get
函数的类
To sort by dob
attribute, you'd do this要按
dob
属性排序,您可以这样做
user_list.sort(key=lambda x: x.dob)
I'd also suggest using dataclasses
or a NamedTuple
rather than define user_dict
, as you're only using this for printing我也建议使用
dataclasses
或NamedTuple
而不是定义user_dict
,因为你只使用这种打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.