鱼C论坛

 找回密码
 立即注册
查看: 1503|回复: 1

[已解决]面向对象的编程求助课后作业求助

[复制链接]
发表于 2021-10-17 16:40:30 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
class ticket():
    def __init__(self,weekend=False,child=False):
        self.qian=100
        if weekend:
            self.inc=1.2
        else:
            self.inc=1
        if child:
            self.discount=0.5
        else:
            self.discount=1
        def price(self,num):
            return self.qian*self.inc*self.discount*num
>>>child=ticket(child=True)
>>> adult=ticket()
print(adult.price(2)+child.price(1))
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    print(adult.price(2)+child.price(1))
AttributeError: 'Ticket' object has no attribute 'price'
课后作业为啥会一直报错呀
最佳答案
2021-10-17 16:47:10
缩进问题,price函数定义要和__init__同级:
  1. class ticket():
  2.     def __init__(self, weekend=False, child=False):
  3.         self.qian = 100
  4.         if weekend:
  5.             self.inc = 1.2
  6.         else:
  7.             self.inc = 1
  8.         if child:
  9.             self.discount = 0.5
  10.         else:
  11.             self.discount = 1

  12.     def price(self, num):
  13.         return self.qian * self.inc * self.discount * num
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-10-17 16:47:10 | 显示全部楼层    本楼为最佳答案   
缩进问题,price函数定义要和__init__同级:
  1. class ticket():
  2.     def __init__(self, weekend=False, child=False):
  3.         self.qian = 100
  4.         if weekend:
  5.             self.inc = 1.2
  6.         else:
  7.             self.inc = 1
  8.         if child:
  9.             self.discount = 0.5
  10.         else:
  11.             self.discount = 1

  12.     def price(self, num):
  13.         return self.qian * self.inc * self.discount * num
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-14 16:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表