Python类的实例化应用实现输入打印

  1. 有五种鲜花,花名和价格,分别是:
    (1)牵牛花(petunia):50
    (2)三色堇(pansy):75
    (3)玫瑰(rose):15
    (4)紫罗兰(violet):50
    (5)康乃馨(carnation):80
    编写一个类,并在程序中实例化该类,调用类中的方法,实现输入购买数量和花名,就能打印出总价。

class flowers:
    data = dict(petunia=50, pansy=75, rose=15, violet=50, carnation=80)

    def get_price(self):
        num = int(input('输入购买数量'))
        name = input('输入购买花名')
        if self.data.get(name, ''):
            price = self.data.get(name, 0) * num
            print(f'{name}的价钱为{price}')
        else:
            print('没有该花')

f = flowers()
f.get_price()

img


如果对你有帮助,可以点击我这个回答右上方的【采纳】按钮,给我个采纳吗,谢谢


class Flowers(object):
    def __init__(self):
        self._priceDict = {"petunia":50,"pansy":75,"rose":15,"violet":50,"carnation":80}
        self._flowerNameDict = {"牵牛花":"petunia","三色堇":"pansy","玫瑰":"rose","紫罗兰":"violet","康乃馨":"carnation"}
    
    def get_price(self):
        count = int(input("请输入购买数量:"))
        name = input("请输入购买花名:")
        # 如果是英文,就直接使用字典获取价格
        perPrice = self._priceDict.get(name)
        if perPrice is not None:
            print("总价是: {}".format(count * perPrice))
        else:
            # 如果输入的是汉字
            newName = self._flowerNameDict.get(name)
            if newName is None:
                print("没有这种花: {}".format(name))
            else:
                perPrice = self._priceDict.get(newName)
                print("总价是: {}".format(count * perPrice))
        
flower = Flowers()
flower.get_price()

img

如果有帮助,请点击下采纳,谢谢~


class Flower:
    price = {}

    def __init__(self):
        self.price['petunia'] = 50
        self.price['pansy'] = 75
        self.price['rose'] = 15
        self.price['violet'] = 50
        self.price['carnation'] = 80

    def print_total_price(self, name, num):
        print(self.price[name] * num)