python 多态的理解

发布时间:2019-03-12 22:59:43编辑:auto阅读(1729)

     1 class Human(object):  # 父类 :创建“人”类
     2 
     3     def __init__(self):
     4 
     5            print('Ill pound the code and buy you a bag')  # 我会敲打码,给你买包包
     6 
     7 class Man(Human):  # 1)子类1 创建“男人”类
     8 
     9     def __init__(self):
    10 
    11            print('In hs, we should have the knowledge to drink wine.The President up, the kitchen down')  # 在衡水,要文武双全,有知识,会喝酒;上的总裁,下的厨房
    12 
    13 class Woman(Human):# 2)子类2 创建“女人”类
    14 
    15     def __init__(self):
    16 
    17            print('If a man loves me, I dont care if he has a house or a car.Woman?Do you believe a')  # 如果男人爱我,我不会在意他有没有房子车子。呵呵女人啊?你信了那只能说明你太天真了。
    18 
    19 print('human:')
    20 
    21 h = Human()
    22 
    23 print('man:')
    24 
    25 m = Man()
    26 
    27 print('woman:')
    28 
    29 w = Woman()  # 分别对 人类、男人类、女人类创建一个变量h、m、w
    30 
    31 print(isinstance(h,Human))#isinstance举例
    32 
    33 print(isinstance(m,Man))
    34 
    35 print(isinstance(m,Human))  #  分别判断h是人类吗、m是男人类吗、m是人类吗,输出结果全部为是。
    36 
    37 #输出结果是:
    38 # human:
    39 # Ill pound the code and buy you a bag
    40 # man:
    41 # In hs, we should have the knowledge to drink wine.The President up, the kitchen down
    42 # woman:
    43 # If a man loves me, I dont care if he has a house or a     
    44      car.Woman?Do you believe a
    45 # True
    46 # True
    47 # True
    View Code

    这就是变量的多态;另外当m调用__init__方法时输出的内容和Human的__init__是不一样的,这就是多态之函数的多态。

    鸭子类型:
    参考鸭子类型,鸭子类型(英语:duck typing)是动态类型的一种风格。在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由"当前方法和属性的集合"决定。这个概念的名字来源于由James Whitcomb Riley提出的鸭子测试,“鸭子测试”可以这样表述:
    “当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。”
    在鸭子类型中,关注的不是对象的类型本身,而是它是如何使用的。例如,在不使用鸭子类型的语言中,我们可以编写一个函数,它接受一个类型为"鸭子"的对象,并调用它的"走"和"叫"方法。在使用鸭子类型的语言中,这样的一个函数可以接受一个任意类型的对象,并调用它的"走"和"叫"方法。如果这些需要被调用的方法不存在,那么将引发一个运行时错误。任何拥有这样的正确的"走"和"叫"方法的对象都可被函数接受的这种行为引出了以上表述,这种决定类型的方式因此得名。
    鸭子类型通常得益于"不"测试方法和函数中参数的类型,而是依赖文档、清晰的代码和测试来确保正确使用。
    综上:鸭子类型,就是使用了貌似不属于自己的方法(其他函数的方法),自己这个 函数,实例化后会改变本质

关键字

上一篇: if 条件判断

下一篇: pycharm clion rider