张图南 发表于 2020-8-9 15:30:37

python第37课 课后习题 动动手0

在类当中的函数能不能调用另一个函数,如果可以,应该怎么做?
我的代码问题出在哪?
class Ticket_price:
    def adult(self,days):
      if 1 <= days <= 5:
            return 100
      else:   
            return 120
    def children(self,days):
      return 0.5 * adult(self,days)

…………………………运行结果…………………………
a = Ticket_price()
>>> a.children(5)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
    a.children(5)
File "D:/PYTHON/python小程序/037-0.py", line 8, in children
    return 0.5*adult(self,days)
NameError: name 'adult' is not defined

zltzlt 发表于 2020-8-9 15:30:57

这样做:

class Ticket_price:
    def adult(self,days):
      if 1 <= days <= 5:
            return 100
      else:   
            return 120
    def children(self,days):
      return 0.5 * self.adult(self,days)

张图南 发表于 2020-8-9 15:37:48

zltzlt 发表于 2020-8-9 15:30
这样做:

不对啊,还是会报错{:10_272:}
a.children()
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
    a.children()
TypeError: children() missing 1 required positional argument: 'days'
>>> a.children(4)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
    a.children(4)
File "D:/PYTHON/python小程序/037-0.py", line 8, in children
    return 0.5 * self.adult(self,days)
TypeError: adult() takes 2 positional arguments but 3 were given

zltzlt 发表于 2020-8-9 15:40:33

张图南 发表于 2020-8-9 15:37
不对啊,还是会报错
a.children()
Traceback (most recent call last):


这样呢?

class Ticket_price:
    def adult(self,days):
      if 1 <= days <= 5:
            return 100
      else:   
            return 120
    def children(self,days):
      return 0.5 * self.adult(days)
页: [1]
查看完整版本: python第37课 课后习题 动动手0