zoukankan      html  css  js  c++  java
  • 零基础学python-15.4 函数的多态vs对象的多态

    这一章节我觉得有必要再来谈一下函数的多态

    1.函数的多态

    指的是函数根据参数的不同而进行不同的运算

    >>> def times(x,y):
    	return x*y
    
    >>> times(2,3)
    6
    >>> times('ray',3)
    'rayrayray'
    >>> 


    我们再来引用昨天的代码,所谓函数的多态,指的是函数会根据参数类型的变化,而且做出不同的运算

    例如上面的代码,第一次times函数引入两个整形参数,得出的结果是整形的乘法

    第二次times引入的是一个字符串一个,一个整数,得出的结果是字符串多次输出

    >>> def times(x,y):
    	return x*y
    
    >>> times('ray','1')
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        times('ray','1')
      File "<pyshell#3>", line 2, in times
        return x*y
    TypeError: can't multiply sequence by non-int of type 'str'
    >>> 


    如果是引入的参数不符合运算规则,python自动报错

    这个时候需要注意:由于运行时才报错,所以会在编码的时候造成一定的影响,因此,在输入前必须检验数据类型,至少要符合运算规则

    2.函数的多态跟对象的多态

    对象的多态指的是父类引用子类对象,下面我举一个java的例子

    public class Test {
    	public static void main(String[] args) {
    		Animal animal = new Bird();
    		animal.say();
    	}
    }
    
    class Animal {
    	public void say() {
    		System.out.println("i am an animal");
    	}
    }
    
    class Bird extends Animal {
    	public void say() {
    		System.out.println("i am an bird");
    	}
    }


    输出结果:

    i am an bird

    但是我们在python里面所说的函数的多态不是上面的特性,而且python也不支持对象的多态

    >>> class Animal(object):
    	def say(self):
    		print('i am an animal')
    
    		
    >>> class Bird(Animal):
    	def say(self):
    		print('i am a bird')
    
    		
    >>> bird = Bird()
    >>> bird.say()
    i am a bird
    >>> 


    由于python在运行的时候自动根据类型Bird赋值给bird,bird直接指向Bird这个类型的对象,所以不会出现多态的情形

    总结:这一章节再次简单的说明函数的多态,以及函数多态跟对象多态之间的区别

    这一章节就说到这里,谢谢大家

    ------------------------------------------------------------------

    点击跳转零基础学python-目录

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Working with WordprocessingML documents (Open XML SDK)
    How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
    Azure:Manage anonymous read access to containers and blobs
    Convert HTML to PDF with New Plugin
    location.replace() keeps the history under control
    On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API
    HTTP Modules versus ASP.NET MVC Action Filters
    解读ASP.NET 5 & MVC6系列(6):Middleware详解
    Content Negotiation in ASP.NET Web API
    Action Results in Web API 2
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896742.html
Copyright © 2011-2022 走看看