python类创建多个实例是同一个实例_从json创建多个python类实例

I am writing some tests to evaluate a rest service

my response is

[

{

"Title_Id": 1,

"Title": "Mr",

"TitleDescription": "Mr",

"TitleGender": "Male",

"Update_Date": "2012-07-21T18:43:04"

},

{

"Title_Id": 2,

"Title": "Mrs",

"TitleDescription": "Mrs",

"TitleGender": "Female",

"Update_Date": "2012-07-21T18:42:59"

},

{

"Title_Id": 3,

"Title": "Sir",

"TitleDescription": "Sir",

"TitleGender": "Male",

"Update_Date": null

}

]

and need to create multiple instance of the class

class TitleInfo:

def __init__(self, Title_Id, Title, TitleDescription, TitleGender, Update_Date ):

self.Title_Id = Title_Id

self.Title = Title

self.TitleDescription = TitleDescription

self.TitleGender = TitleGender

self.Update_Date = Update_Date

what I have done is

def GetTitle(self):

try:

response = *#......"The string shown above"*

if isinstance(response, str) :

Records = json.loads(response)

RecTitles = []

for num in range(0, len(Records)):

RecTitle =TitleInfo(Records[num]['Title_Id'],Records[num]['Title'],Records[num]['TitleDescription'],Records[num]['TitleGender'],Records[num]['Update_Date'])

RecTitles.append(RecTitle)

This is working fine ....I need to know is there more short and sweet way to do that?

解决方案

You could just unpack each dict and give that as an argument to TitleInfo:

RecTitles = [TitleInfo(**x) for x in json.loads(response)]

Here's the explanation from Python tutorial:

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):

... print("-- This parrot wouldn't", action, end=' ')

... print("if you put", voltage, "volts through it.", end=' ')

... print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值