如何从用户输入访问类对象及其属性?

2024-06-09 19:10:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始编程,我决定使用Python进行第一次编码尝试,现在我正在练习使用类和对象。 如果我要问的问题以前有人问过,我很抱歉,但是我好像到处都找不到答案,所以就这样吧。你知道吗

我有一个包含类的文件。下面是我写的完整代码:

#class file
#class prodotti  refers to "register" with products in stock and their prices

class Prodotti(): #class Prodotti() contains products from register and their relative specs 
def __init__(self, nome="", #name of product
                   prezzo=0, #product price
                   quantità=0,): #stock quantity of product
    self.nome=nome
    self.prezzo=prezzo
    self.quantità=quantità

def newproduct(self): #method appends new product and its specs to the end of this file
      name=input("Inserire nuovo prodotto: ")
      f=open("cassa3.py", "a")
      f.write(name + "=Prodotti(nome='" + name + "', ")
      price=input("Inserire prezzo prodotto: ")
      f.write("prezzo=" + price + ", quantità=0)\n")
      f.close()

def tellprice(self): #method should return price of object
    inp=input("Di quale prodotto vuoi conoscere il prezzo? ") #asks user which product they want to know the price of
    if inp=Prodotti():
       print(inp.prezzo)

#class objects
#user can insert new products that are saved below
tortino=Prodotti(nome="Tortino al cioccolato", prezzo=3.4, quantità=0)
muffincioccolato =Prodotti(nome="Muffin al cioccolato", prezzo=1.8, quantità=0)
cupcake=Prodotti(nome='cupcake', prezzo=2, quantità=0)

在另一个保存在同一目录中的文件中,我有一个主程序:

from cassa3 import Prodotti #file cassa3.py in same directory as this file



if __name__=="__main__":
P=Prodotti()
P.tellprice()

从上面的代码可以看出,我想要tellprice()方法做的是询问用户他们想知道什么产品的价格。 但是,我只是不知道如何使用户输入与类对象相对应,以便访问它的属性。 有人能解释一下我是怎么做到的吗?你知道吗

提前谢谢。你知道吗


Tags: andoftonameselfdefproductprice
2条回答

在您能够解决这个问题之前,您需要解决您的设计问题。你知道吗

你的评论说# class Prodotti() contains products from register and their relative specs,但不完全正确。这个类包含一个产品及其名称、价格和数量。你知道吗

您将需要定义另一个类(可能是Register),该类将实际存储产品的列表(如果产品名称对于有效查找是唯一的,则为字典),或者其他任何类型的产品(实例Prodotti)。你知道吗

tellprice方法目前毫无意义。它只是创建一个Prodotti的新实例,而if条件将永远不会是True。你知道吗

另外,强烈建议在代码中使用英文名称。你知道吗

考虑以下示例作为一般指南:

class Product:
    def __init__(self, name, price,  quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    # (... some other methods ... )

class Register:
    def __init__(self, products):
        # this will store the products in a dictionary with products names as keys
        # and Product instances as values for an efficient look up by tell_price
        self.products = {product.name: product for product in products}

    def tell_price(self):
        name = input('Which product would you like to know the price of?')
        # this will raise KeyError if user inputs a non-existing product name
        # and should be caught, or use .get(...) instead
        return self.products[name].price


apple = Product('apple', 1, 10)
banana = Product('banana', 2, 2)

register = Register([apple, banana])

print(register.tell_price())

# Which product would you like to know the price of?
>> apple
# 1

我不会让你的价格包括用户输入。你知道吗

def tellprice(self): #method should return price of object
    return self.price

然后大体上(这是非常简化的):

inp = input("Di quale prodotto vuoi conoscere il prezzo? ")
print(inp.tellprice)

显然,这是假设他们输入了正确的产品名称,所以一些向用户指出他们不正确的方法可能是有用的

相关问题 更多 >