微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么什么都没打印出来?

如何解决为什么什么都没打印出来?

我是python的新手,所以我认为这可能是个简单的问题,但这使我感到困惑。这是我的代码

# Mike Fitzgibbon CS4250 Project4 implement class diagram
# define the class
class Product:
    # name is the name of the product
    name = None
    # price is how much the product costs
    price = None
    # discount percent is how much the discount is in percentages
    discountPercent = None
    # define the constructor

    def __init__(self,n,p,d):
        # initialize variables
        self.name = n
        self.price = p
        self.discountPercent = d

    # define get discount by returning the discount
    def getdiscountAmount(self):
        return self.discountPercent

    # define discount price by returning the discount percent times the price
    def getdiscountPrice(self):
        return self.discountPercent*self.price

    # define get description by creating description using field variables
    def getDescription(self):
        print("Name: "+self.name)
        print("Price: "+self.price)
        print("discount: "+self.discountPercent+"%")
        print("discount price: "+self.getdiscountPrice())
        
        
def __main__():
    p=Product("A",100,90.0)
    print(p.getDescription())

当我运行此代码时,什么都不会打印出来。为什么?我该如何解决

解决方法

您需要添加;

if name == '__main__':
    main()

这样做的原因是您定义了main函数,但没有告诉计算机运行它。

,

要运行__main__()函数,可以将其添加到程序的末尾:

if __name__ == "__main__":
   __main__()

要打印值,请将print(p.getDescription())更改为p.getDescription(),因为在类中调用该函数将输出这些值。顺便说一句,您不能将int / float与str并置,因此您应该将int / float转换为字符串,例如print("Price: "+str(self.price))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。