【问题标题】:How to create instance variable and use inside the class?如何创建实例变量并在类中使用?
【发布时间】:2018-09-12 03:53:51
【问题描述】:

如何从下面的列表中创建一个实例变量,其中包含一个名为 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)

【问题讨论】:

  • 你让我们猜测错误是什么以及在哪里。编辑您的问题以包含完整的错误消息。
  • 可选地self上设置price属性但总是price_book方法中读取它。您的代码可能导致 AttributeError
  • @JohnGordon ,更新
  • @GrijeshChauhan ,是的,我想正确设置它,但选项用完了
  • v[0:][1]v[1] 相同,顺便说一句。

标签: python python-3.x dictionary


【解决方案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}

【讨论】:

  • 是的,我按照这个并在 2 中进行了更新,这是正确的做法
  • 很高兴为您提供帮助!
  • 在这里,我需要解压缩每个键,它可能最终会变成一个长编码。我想说的是没有 pythonic
  • 您项目的下一个目标是什么?你想解开哪些钥匙,你想用它们做什么?
  • 看看,不确定这是否是你的目标,但从我们的谈话中,这就是我总结的结果
【解决方案2】:
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]

【讨论】:

  • 该方法返回最后一件商品的价格
  • @Karamzov 我认为这是故意的。 self.price 显然无法存储多个项目。此外,上面的代码显然没有在 OP 中的 kwargs 循环下面缩进。
  • 如何创建一个名为 self.price 的列表并将所有值存储在那里
  • @Karamzov 这可能会更好,但我只是使用问题中的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多