简体   繁体   English

如何在 Python 中的普通 class 中使用数据类中的特定变量?

[英]How do I use a specific variable from a dataclass in a normal class in Python?

So I want to make a class that functions as a bag.所以我想做一个 class 作为一个包。 I simply want to make 2 functions in that bag: one function that adds an item in the bag and adds a specified amount and a function that takes out an item and the specified quantity of that item.我只想在那个包里做 2 个功能:一个 function 在包中添加一个项目并添加指定数量,一个 function 取出一个项目和该项目的指定数量。

For the adding an item function, I want to be able to add a new item with a certain quantity and if that item is already in the list, the quantity put in is added to the existing quantity of that item.对于添加项目 function,我希望能够添加具有一定数量的新项目,如果该项目已经在列表中,则将放入的数量添加到该项目的现有数量中。

For the taking out an item function, if the quantity that wants to be taken out of the bag is the same as the amount already in the bag, the item is deleted from the list.对于取出物品function,如果要取出的数量与已放入袋子的数量相同,则将该物品从列表中删除。 If the amount that wants to be taken out is less than the amount in the bag, the quantity of that item decreases.如果要取出的数量少于袋子中的数量,则该物品的数量会减少。 If the quantity that wants to be taken out is more than what is in the bag, there is a simple error message.如果要取出的数量多于袋子中的数量,则会出现简单的错误消息。 And of course, if the item that wants to be taken out is not in the list, there is an error message.当然,如果要取出的项目不在列表中,则会出现错误消息。

The bag uses a list to store the items.袋子使用列表来存储物品。 I want the items to use a dataclass to store the quantity and the name of the item.我希望项目使用数据类来存储项目的数量和名称。 I made this already:我已经做了这个:

from dataclasses import dataclass

@dataclass
class Item:
    amount: int
    item1: str


class Bag:
    def __init__(self):
        self.liste_item = []

    def add_item(self, item, quantity):
        if item in self.liste_item:
            Item.amount += quantity
        else:
            self.liste_item.append(Item(quantity, item))
        print(self.liste_item)

    def take_item(self, item, quantity):
        if item in self.liste_item:
            if Item(quantity, item).amount == quantity:
                del item
            elif Item(quantity, item).amount < quantity:
                print(f"You do not have {quantity} {item} in your bag.")
            else:
                Item.amount -= quantity
        else:
            print(f"{item} is not in your bag.")
        print(self.liste_item)

This code does not work.此代码不起作用。 The problem is I don't know how to use and change a specific variable's attributes from a dataclass.问题是我不知道如何使用和更改数据类中特定变量的属性。 In this case it's changing the quantity of a specific item.在这种情况下,它正在更改特定项目的数量。 The other problem I have is I don't know how to say "If this quantity of this item is in the bag..." or even the line:我遇到的另一个问题是我不知道该怎么说“如果这个数量的这个物品在包里......”甚至是行:

if item in self.liste_item:

In this line I want to check whether the specific item is in the list.在这一行中,我想检查特定项目是否在列表中。 The problem is that it simply doesn't work and the code thinks that the item which is in the bag, is not in the bag.问题是它根本不起作用,并且代码认为袋子里的物品不在袋子里。 It only works when I make the change:它仅在我进行更改时才有效:

if item not in self.liste_item:

Which makes no sense to me.这对我来说毫无意义。 Please help me with this.请帮我解决一下这个。

Item.amount isn't a class attribute; Item.amount不是 class 属性; it's just a quasi-declared instance attribute.它只是一个准声明的实例属性。 The purpose of the dataclass decorator is to use the contents of the class statement in a fairly invasive way to create the "actual" class used later in your program.数据类装饰器的目的class dataclass的内容来创建稍后在程序中使用的“实际” class。 Part of that process is automatically generating Item.__init__ along the lines of该过程的一部分是自动生成Item.__init__沿线

def __init__(self, amount, item1):
    self.amount = amount
    self.item1 = item1

As such, you should not be adding anything to Item.amount directly.因此,您不应该直接向Item.amount添加任何内容。 You need to find the corresponding instance in self.liste_item and update it.需要self.liste_item中找到对应的实例并更新。

from dataclasses import dataclass


@dataclass
class Item:
    amount: int
    item1: str


class Bag:
    def __init__(self):
        self.liste_item: list[Item] = []

    def add_item(self, item_name: str, quantity: int):
        for item in self.liste_item:
            if item.item1 == item_name
                item.amount += quantity
                break
        else:
            # Create a new Item instance if no match was found.
            self.liste_item.append(Item(quantity, item_name))

    ...

take_item must be rewritten similarly. take_item必须以类似方式重写。

class Bag:
    bag = {}


def add_item(self, new_item, quantaty):
    if new_item in self.bag:
        self.bag[new_item] += quantaty
        else:
            self.bag[new_item] = quantaty
        
def remove_item(self, item, quantaty):
        if item in self.bag:
            if quantaty > self.bag[item]:
                print(f"Only {self.bag[item]} of {item} left. Cant substract {quantaty}")
            else:
                self.bag[item] -= quantaty
        else:
            pass
        


Kevin = Bag()

Kevin.add_item("sword", 10)
print(Kevin.bag)
Kevin.add_item("sword", 10)
print(Kevin.bag)
Kevin.add_item("stone", 10)
print(Kevin.bag)

Kevin.remove_item("stone", 5)
print(Kevin.bag)
Kevin.remove_item("stone", 6)
print(Kevin.bag)

Clould be like that.云应该是这样的。 U can try it out.你可以试试看。 I just coded this for you Im using a Dictonary to safe all.我刚刚为您编写了此代码,我使用字典来保护所有人。 Hope u can see how u can access the variable:) Got ua picture cuz im to dump to get it here right xD希望您能看到您如何访问该变量:) 得到 ua 图片因为我要转储以将其放在这里 xD在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM