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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python用装饰器自动注册Tornado路由详解

第一个版本 在这个版本中,首先创建了 RouterConfig 对象,其构造方法创建了 tornado.web.Application() 并赋值为 self.Application ,...

Python使用scipy模块实现一维卷积运算示例

本文实例讲述了Python使用scipy模块实现一维卷积运算。分享给大家供大家参考,具体如下: 一 介绍 signal模块包含大量滤波函数、B样条插值算法等等。下面的代码演示了一维信号的...

使用pyecharts生成Echarts网页的实例

pyecharts是一个封装百度开源图表库echarts的包,使用pyecharts可以生成独立的网页,也可以在flask、django中集成使用。 示例如下: from pyech...

scikit-learn线性回归,多元回归,多项式回归的实现

scikit-learn线性回归,多元回归,多项式回归的实现

匹萨的直径与价格的数据 %matplotlib inline import matplotlib.pyplot as plt def runplt(): plt.figure()...

python常用web框架简单性能测试结果分享(包含django、flask、bottle、tornado)

测了一下django、flask、bottle、tornado 框架本身最简单的性能。对django的性能完全无语了。 django、flask、bottle 均使用gunicorn+g...