【问题标题】:How to get a total from with "Class" in python, then calling it into another file main()?如何从python中的“Class”中获取总数,然后将其调用到另一个文件main()中?
【发布时间】:2021-06-18 10:59:39
【问题描述】:

我的任务是:假设您销售 T 恤(或任何其他物品),并且所有 T 恤的价格都相同,它们都具有相同的价格

定义一个名为 Sale 的类。构造函数的第一行只有 3 个参数:self、item 和数量。此外,构造函数有一个价格属性和一个保存销售总额的属性。

该程序假定每件商品的价格相同,因此您可以使用您选择的价格在 init 中初始化价格。就像我们在讲座中展示的汽车示例一样,在 init 中将 speed 属性初始化为零,您可以将 total 初始化为零

该类应该有 4 个方法来:

一种计算总数的方法 返回总数的方法 返回项目的方法 一种退货数量的方法 使用此类导入文件的程序需要创建 Sale 类的实例。假设具有类定义的文件是 sale.py 并且类是 Sale,它看起来像这样

new_sale = sale.Sale('Men medium blue', 10)

当我运行创建类实例的程序时,假设类中的价格设置为 9.99,输出将如下所示

new_sale = sale.Sale('Men medium blue', 10)

10 件 T 恤男士中蓝色的总价为 99.9 美元

'''类销售:

def __init__(self,item,quantity):
    self.item=item
    self.quantity=quantity
    self.total=self.price*self.quantity
    self.price=10
def get_item(self):
    return self.item

def get_quantity(self):
    return self.quantity

def get_total(self):
    return self.total

''' 这是我在另一个文件中的主要功能,我试图让用户输入的数量乘以 Class 中的设定价格(10 美元)

'''

进口销售

def main():

itemQ=input("Please enter type of t-shirt: ")
quanT=int(input("Please insert number of t-shirt you wish to buy: "))

theSale= sale.Sale(itemQ, quanT)

print("The item is ", theSale.get_item(), " and a quantity of ", theSale.get_quantity(), "and total of ", theSale.get_total())

main()

'''

【问题讨论】:

    标签: python class


    【解决方案1】:

    一些小的改动应该可以让它工作:

    # sale.py
    def __init__(self, item, quantity):
        self.item=item
        self.quantity=quantity
        self.price=10
        self.total=self.price*self.quantity # you have to define price before you use it to calculate the total
    
    # add these two lines at the end of you main .py file
    if __name__ == '__main__':
        main()
    
    

    在 main 方法上查看 python 文档:main

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2022-01-26
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多