Python基础编程.pptVIP

  • 22
  • 0
  • 约5.82千字
  • 约 41页
  • 2017-05-28 发布于上海
  • 举报
Python基础编程ppt课件

继承 定义子类 class Sharpei(Dog): def __init__(self): self.sound = ao~ao~ suobi = Sharpei() suobi.bark() 此时运行 niub.bark()? 说明:子类之间的属性不会互相影响 继承 定义子类 如果执行如下语句: suobi1 = Sharpei() suobi1.sound = kao~kao~ 此时再执行 soubi.bark()? 说明:实例之间的属性也不会互相影响 继承 更复杂的复用例子 class Dog(object): def __init__(self): self.sound = wang~wang~~ self.paw = sharp self.jaw = long def bark(): ... class Sharpei(Dog): def __init__(self): Dog.__init__(self) self.sound = ao~ao~ 继承 类、子类和实例的关系 术语 inheritance, is-a 沙皮狗 is-a 狗 suobi is-a 沙皮狗 比较 composition, has-a? —— 属性也可以是一个类的实例(instance) 继承 类、子类和实例的关系 继承 名字空间在类中的表现 class Dog: paw = None def __init__(self): self.sound = wang~wang~~ self.fur = print This is a Dog: %s % self.sound def grow(self): self.teeth = white 继承 名字空间在类中的表现 class Husky(Dog): brain = 0.9 def __init__(self): Dog.__init__(self) # super(Husky, self).__init__() # SAME EFFECT BUT BETTER self.sound = woo~~wooo~~~~~~ self.fur = +++ print This is a Husky: %s, fur: %s % (self.sound, self.fur) def grow(self): self.paw = grey fold self.teeth = white sharp self.fur = grey long def work(self): self.paw = white unfold self.muscle = 0.9 继承 名字空间在类中的表现 print “\ntest 1 links print niub.__dict__: %s % niub.__dict__ print niub.__class__: %s % niub.__class__ print Husky.__bases__: %s % Husky.__bases__ print “\ntest 2 namespace print niub.__dict__: %s % niub.__dict__ print Husky.__dict__: %s % Husky.__dict__ print Dog.__dict__: %s % Dog.__dict__ print “\ntest 3 __dict__ changes niub.grow() print after grow(): print \tniub.__dict__: %s % niub.__dict__ print \tHusky.__dict__: %s % niub.__dict__ print \tDog.__dict__: %s % Dog.__dict__ niub.work() print “when work(): print \tniub.__dict__: %s % niub.__dict__ print \tHusky.__dict__: %s % niub.__dict__ print \tDog.__dict__: %s % Dog.__dict__ 继承 名字空间在类中的表现 结果说明 继承 类、子类和实例的关系 继承 名字空间在类中的表现 __dict__ 是内置的属性 本质:目录索引 使用 __class__ 和 __bases__ 向

文档评论(0)

1亿VIP精品文档

相关文档