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

时间:2017-11-12 13:22:32

标签: python class object

我刚刚开始编程,我决定使用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()要做的是询问用户他们想知道哪些产品的价格。 但是,我只是不知道如何使用户输入对应一个类对象,这样我就可以访问它的属性了。 有人可以解释我怎么能做到这一点?

提前致谢。

2 个答案:

答案 0 :(得分:1)

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

你的评论是# 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

答案 1 :(得分:-1)

我不会让你的tellprice包括用户输入。

public class HomeController : BaseController
{

    private readonly IViewRenderService _viewRenderService;

    public HomeController(CryptoDateContext context, IConfiguration configuration,
        IViewRenderService viewRenderService, IOptions<GeneralSettings> generalSettings, ILogger<BaseController> logger)
        : base(context, configuration, generalSettings, logger)
    {
        logger.LogDebug("Base controller ctor called");
        _viewRenderService = viewRenderService;

    }

    public IActionResult Sitemap()
    {


    }

    public async Task<IActionResult> SymbolSitemap()
    {

    }




    [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult GetSearchResults(SearchCriteria criteria)
    {


    }
    public IActionResult Index()
    {

    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddEvent(SubmitEventModel model)
    {

    }


    public IActionResult SubmitEvent(int? id)
    {

    }

    public IActionResult DownloadICS(int id)
    {



    }
    [HttpPost]
    [ServiceFilter(typeof(ValidateReCaptchaAttribute))]
    public IActionResult SubmitContactus(ContactUsModel model)
    {

    }

    public IActionResult Contribute()
    {


        return View();
    }
    public IActionResult Telegram()
    {


        return View();
    }
    [Route("home/event/{id:int}/{title?}")]
    public IActionResult Event(int id, string title = null)
    {

    }
    [Route("home/coin/{symbol:alpha}/{name?}")]
    public IActionResult Symbol(string symbol, string name = null)
    {

    }

    public IActionResult Contact()
    {

    }

    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
    public IActionResult Exception()
    {
        throw new Exception("Testing");
    }
}

然后在main(这显着简化):

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

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