# coding:utf-8 class Parent(object): def talk(self): print('talk') def think(self): print('think') class Child(Parent): def swiming(self): print('child can swimming') c = Child() c.talk() c.swiming() p = Parent() p.talk() # p.swiming() # 报错
# coding:utf-8 # 继承的例子 class Parent(object): def __init__(self, name, sex): self.name = name self.sex = sex def talk(self): return f'{self.name} are walking' def is_sex(self): if self.sex == 'boy': return f'{self.name} is a boy' else: return f'{self.name} is a girl' class ChildOne(Parent): def play_football(self): return f'{self.name} are playing football' class ChildTwo(Parent): def play_pingpong(self): return f'{self.name} are playing pingpong' c_one = ChildOne(name='xm', sex='boy') result = c_one.play_football() print(result) result = c_one.talk() print(result) result = c_one.is_sex() print(result) print('--------------------------------') c_two = ChildTwo(name='ym', sex='girl') result = c_two.play_pingpong() print(result) result = c_two.talk() print(result) result = c_two.is_sex() print(result) print('---------------------------------') p = Parent(name='xym', sex='boy') result = p.talk() print(result) result = p.is_sex() print(result) # result = p.play_football() # 报错 # print(result)
多态的用法:子类中重写父类的方法。
# coding:utf-8 # 1.定义一个父类 class XFather(object): def talk(self): print('X的爸爸说了一句话') def jump(self): print('大家都可以跳') # 2.定义一个子类,并且继承一个父类 class XBrother(XFather): def run(self): print('XBrother在奔跑着..') def talk(self): # 重写父类中的函数的意思是:函数名不发生变化,但是内容发生了变化 print('XBrother在说话..') class X(XFather): def talk(self): print('hhh, X也可以开心的说自己的观点') if __name__ == "__main__": X_Brother = XBrother() X_Brother.run() X_Brother.talk() X_Brother.jump() father = XFather() father.talk() X1 = X() X1.talk() X1.jump()
为什么要去多态?为什么要去继承父类