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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

TensorFlow查看输入节点和输出节点名称方式

TensorFlow 定义输入节点名称input_name: with tf.name_scope('input'): bottleneck_input = tf.place...

python中List的sort方法指南

简单记一下python中List的sort方法(或者sorted内建函数)的用法。  List的元素可以是各种东西,字符串,字典,自己定义的类等。 sorted函数用法如下:...

tensorflow实现图像的裁剪和填充方法

tensorflow实现图像的裁剪和填充方法

tensorflow里面提供了实现图像进行裁剪和填充的函数,就是tf.image.resize_image_with_crop_or_pad(img,height,width )。img...

python分析作业提交情况

python分析作业提交情况

这次做一个比较贴近我实际的东西:python分析作业提交情况。 要求:     将服务器中交作业的学生(根据文件的名字进行提取)和统计成绩的表格中...

Python内置函数bin() oct()等实现进制转换

使用Python内置函数:bin()、oct()、int()、hex()可实现进制转换。 先看Python官方文档中对这几个内置函数的描述: bin(x) Convert an inte...