如何创建实例变量并在类内部使用?

时间:2018-09-11 12:06:11

标签: python python-3.x dictionary

如何从下面的列表中创建一个实例变量,该实例变量包含一个名为price的字典键,我正尝试使用一个名为Library的类来检索所有书籍的价目表

1)这是书籍及其详细信息的列表

data = { "books" : [ { "number_of_pages" : 849,
        "price" : 13.550000000000001,
        "publish_date" : 2011,
        "subjects" : [ "Time travel",
            "Assassination"
          ],
        "title" : "11/22/63"
      },
      { "number_of_pages" : 732,
        "price" : 7.9900000000000002,
        "publish_date" : 1999,
        "subjects" : [ "Authors",
            "Custody of children",
            "Grandfathers",
            "Haunted houses",
            "Novelists",
            "Trials (Custody of children)",
            "Widowers",
            "Widows",
            "Writer's block"
          ],
        "title" : "Bag of bones"
      },]}

2)我创建了一个名为Library的类,该类将解压缩列表并存储变量

class Library:
    def __init__(self,**kwargs):

        for k, v in kwargs.items():
            setattr(self, k, v)
            #print(k,v)
        if 'price' in v[0:][1]:
              for c in v[0:][1].items():
                  if 'price' in c:
                    self.price=c['price']


    def price_book(self):
         return self.price

    def __float__(self):
        return self.price


Libra = Library(**data)
Price=Libra.price_book()
print(Price)

在尝试使用实例返回时,重新调整了为变量设置价格的错误吗?

如何设置实例变量并检索库中的价格列表?

致谢

更新1:

self.price = c ['price']

TypeError:元组索引必须是整数或切片,而不是str

更新2:

class Library:
    def __init__(self,**kwargs):

        for k, v in kwargs.items():
                setattr(self, k, v)

        self.price = []
        for k, v in kwargs.items():
            for i in range(len(v)):
                self.price.append(v[i]['price'])

    def price_book(self):
         return self.price

    def discount_book(self):
         self.price=self.price
         return  list(map((lambda x: x -2), self.price))

    def __float__(self):
        return self.price

Libra = Library(**data)
Price=Libra.price_book()
Pri=Libra.discount_book()
print(Price)
print(Pri)

2 个答案:

答案 0 :(得分:1)

if 'price' in v[0:][1]:
    for c in v[0:][1].items():
        if 'price' in c:
            self.price=c['price']

字典的items()方法将键值对作为元组返回。

因此,c是一个元组,例如('price', 7.99)

通过整数而不是字符串对字符串进行索引。

您可能想要self.price = c[1]

答案 1 :(得分:1)

如果要获取价格或将其设置为实例,就很难看到挂断的电话。

def __init__(self, **kwargs):

    for k, v in kwarg.items():
        setattr(self, k, v)

    self.price = []
    for k, v in kwargs.items():
        for i in range(len(v)):
            self.price.append(v[i]['price'])
(xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py 
[13.55, 7.99]

请求提出建议

我不会做的一件事,因为我不确定我认为使用data会产生不必要的嵌套,除非您要使用books并说出movies您可以将整个过程称为books并删除一层嵌套。同样,该方法记录重复项,我使用set解决了这个问题,但是您可以避免使用更多代码附加重复项,因为仍然不确定整个任务,因此不想做太多。

但是,如果目标只是为每个数据创建这些列表,则此代码将起作用:

pages = []
publish_dates = []
subjects = []
titles = []
prices = []

for v in data.values():
    for i in range(len(v)):
       for w, x in v[i].items():
            pages.append(v[i]['number_of_pages'])
            publish_dates.append(v[i]['publish_date'])
            titles.append(v[i]['title'])
            prices.append(v[i]['price'])
            for a in v[i]['subjects']:
                subjects.append(a)

print(f"Pages: {set(pages)}\nPublish Dates: {set(publish_dates)}\n" \
      f"Subjects: {set(subjects)}\nTitles:{set(titles)}\n" \
      f"Prices: {set(prices)}")

输出

(xenial)vash@localhost:~/python/AtBS$ python3.7 comphren.py 
Pages: {849, 732}
Publish Dates: {2011, 1999}
Subjects: {'Time travel', 'Widows', 'Authors', 'Widowers',
'Assassination', 'Haunted houses', 'Grandfathers', "Writer's block",
'Novelists', 'Trials (Custody of children)', 'Custody of children'}
Titles:{'11/22/63', 'Bag of bones'}
Prices: {13.55, 7.99}