设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

【Python 第50课】 面向对象(4)

[复制链接]

0

主题

0

好友

64

积分

注册会员

Rank: 2

楼主
发表于 2016-3-13 09:19:53 |显示全部楼层
本帖最后由 弹星者 于 2016-3-13 09:26 编辑
  1. class Vehicle:
  2.     def __init__(self, speed):
  3.         self.speed = speed

  4.     def drive(self, distance):
  5.         print 'need %f hour(s)' % (distance / self.speed)

  6. class Bike(Vehicle):
  7.     pass

  8. class Car(Vehicle):
  9.     def __init__(self, speed, fuel):
  10.         Vehicle.__init__(self, speed)
  11.         self.fuel = fuel

  12.     def drive(self, distance):
  13.         Vehicle.drive(self, distance)
  14.         print 'need %f fuels' % (distance * self.fuel)

  15. b = Bike(15.0)
  16. c = Car(80.0, 0.012)
  17. b.drive(100.0)
  18. c.drive(100.0)

  19. d=Car(80,None)
  20. d.Vehicle.drive(100)

  21. #下面是运行报错
  22. '''
  23. need 6.666667 hour(s)
  24. need 1.250000 hour(s)
  25. need 1.200000 fuels
  26. <blockquote>Traceback (most recent call last):
复制代码
在crossin老师代码的最后添加了两行,想尝试一下子类调用父类里的函数,然而运行的时候报错了,这个错误为什么呀(代码复制的时候没复制好,在楼下重发一个
回复

使用道具 举报

0

主题

0

好友

64

积分

注册会员

Rank: 2

沙发
发表于 2016-3-13 09:27:47 |显示全部楼层
  1. class Vehicle:
  2.     def __init__(self, speed):
  3.         self.speed = speed

  4.     def drive(self, distance):
  5.         print 'need %f hour(s)' % (distance / self.speed)

  6. class Bike(Vehicle):
  7.     pass

  8. class Car(Vehicle):
  9.     def __init__(self, speed, fuel):
  10.         Vehicle.__init__(self, speed)
  11.         self.fuel = fuel

  12.     def drive(self, distance):
  13.         Vehicle.drive(self, distance)
  14.         print 'need %f fuels' % (distance * self.fuel)

  15. b = Bike(15.0)
  16. c = Car(80.0, 0.012)
  17. b.drive(100.0)
  18. c.drive(100.0)

  19. d=Car(80,None)
  20. d.Vehicle.drive(100)

  21. #下面是报错
  22. '''
  23. need 6.666667 hour(s)
  24. need 1.250000 hour(s)
  25. need 1.200000 fuels
  26. Traceback (most recent call last):
  27.   File "123.py", line 26, in <module>
  28.     d.Vehicle.drive(100)
  29. AttributeError: Car instance has no attribute 'Vehicle'
  30. '''
复制代码
在crossin老师代码的最后添加了两行,想尝试一下子类调用父类里的函数,然而运行的时候报错了,这个错误为什么呀
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-7 10:05 , Processed in 0.026832 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部