Home  >  Article  >  Backend Development  >  Python基类函数的重载与调用实例分析

Python基类函数的重载与调用实例分析

WBOY
WBOYOriginal
2016-06-10 15:18:26908browse

本文实例讲述了Python基类函数的重载与调用方法。分享给大家供大家参考。具体分析如下:

刚接触Python语言的时间不长,对于这个语言的很多特性并不是很了解,有很多用法都是还不知道。今天想着写一个Python面向对象编程时的继承中的函数调用。分享出来,一起进步。

因为之前接触过Java和C++,所有对于面向对象的思想也早已经很熟析的了。这里也不再对面向对象是什么进行赘述了。我们直接上代码吧!看看对于继承和基类函数的调用在Python中是如何调用的~

首先,是基类文件base.py

复制代码 代码如下:
'''
Created on Dec 18, 2014

@author: raul
'''

class animal(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        print 'animal init'
       
    def say(self):
        print 'animal say'

然后,是子类文件child.py

复制代码 代码如下:
'''
Created on Dec 18, 2014

@author: raul
'''
from inheritance.base import animal

class cat(animal):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
#         animal.__init__()
        animal.__init__(self)
        print 'cat init'
       
    def say(self):
        animal.say(self)
        print 'cat say'

if __name__ == '__main__':
    c = cat()
    c.say()

运行后,就可以看到输出,如下:

animal init
cat init
animal say
cat say

这就说明,我们的继承和函数的调用都已经OK了

此例子比较简单,不过基本上也讲明白了Python基类函数的重载与调用,希望学习的同学可以举一反三。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn