繁体   English   中英

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

[英]How to access a class object and its attributes from user input?

我刚开始编程,后来我决定使用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()要做的是询问用户他们想知道哪种价格。 但是,我只是不知道如何使用户输入与类对象相对应,因此我可以访问其属性。 有人可以解释我如何做到这一点吗?

提前致谢。

在您能够解决此问题之前,您将需要解决您的设计问题。

您的评论中说# 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)

显然,这是假设他们输入了正确的产品名称,因此可以通过某种方式向用户表明他们不正确

暂无
暂无

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

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