zoukankan      html  css  js  c++  java
  • Python学习-类的继承

     1 继承:
     2 #python2 经典类是按深度优先来继承的,新式类是按广度优先来继承的
     3 #python3 经典类和新式类都是按广度优先来继承的
     4 
     5 
     6 
     7 #经典类:class People:
     8 class People(object):  #这个是新式类,多继承的时候有了改变
     9 
    10     def __init__(self, name, age):
    11         self.name =name
    12         self.age = age
    13 
    14 
    15     def eat(self):
    16         print("%s is eating" % self.name)
    17 
    18 
    19     def talk(self):
    20         print("%s is talking" % self.name)
    21 
    22     def sleep(self):
    23         print("%s is sleeping" % self.name)
    24 
    25 #多继承的示范
    26 class Relation(object):
    27     def make_friends(self, obj):
    28         print("%s is making friends with %s" % (self.name, obj.name))
    29         self.friends.append(obj)  #要用obj,这样才和另一个实例产生联系
    30 
    31 #子类继承
    32 class Man(People, Relation):  #小括号中 一定要有父类名称,如People
    33 
    34     def __init__(self, name, age, sex="man"):
    35 #        People().__init__(self,name, age) 第一种的初始化方法
    36         super().__init__(name, age)  # superclass,super函数直接继承所有,super(Man, self)的省略
    37         self.sex = sex
    38         self.friends = []
    39 
    40     def working_hard(self):
    41         print("earning money.")
    42 
    43     def sleep(self):   #重构了父类的方法
    44         People.sleep(self)
    45         print("Man %s is sleeping" % self.name)
    46 
    47 
    48 class Woman(People, Relation):
    49 
    50     def __init__(self,name, age, sex = "woman"):
    51         super().__init__(name, age)
    52         self.sex = sex
    53         self.friends = []
    54 
    55     def get_birth(self):
    56         print("%s is giving birth to a baby." % self.name)
    57 
    58 
    59 p1 = People("Adam", 26)
    60 p1.eat()
    61 print("%s is %s years old." % (p1.name, p1.age))
    62 p1.sleep()
    63 
    64 m1 = Man("Alex", 28)
    65 m1.eat()
    66 m1.working_hard()
    67 m1.sleep()
    68 m1.make_friends(p1)
    69 print(m1.friends[0].name)
    70 
    71 w1 = Woman("Shell", 27)
    72 w1.get_birth()
    73 w1.sleep()
  • 相关阅读:
    【FICO系列】SAP FICO 基本概念
    【MM系列】SAP 的库存管理
    【ABAP系列】SAP ABAP WRITE字段隐藏的方法
    【BASIS系列】SAP 批量锁住用户和TCODE的方法
    【HANA系列】SAP HANA 1.0 SPS 11 新特性
    【HANA系列】SAP HANA启动出现ERROR
    瓣呀,一个开源项目
    javascript入门笔记6-内置对象
    javascript入门笔记5-事件
    javascript入门笔记4-数组
  • 原文地址:https://www.cnblogs.com/Ian-learning/p/8325432.html
Copyright © 2011-2022 走看看