我刚开始编程,我决定使用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
。你知道吗另外,强烈建议在代码中使用英文名称。你知道吗
考虑以下示例作为一般指南:
我不会让你的价格包括用户输入。你知道吗
然后大体上(这是非常简化的):
显然,这是假设他们输入了正确的产品名称,所以一些向用户指出他们不正确的方法可能是有用的
相关问题 更多 >
编程相关推荐