Python中的面向对象编程详解(下)


Posted in Python onApril 13, 2015

继承

继承描述了基类的属性如何“遗传”给派生类。一个子类可以继承它的基类的任何属性,不管是数据属性还是方法。
创建子类的语法看起来与普通(新式)类没有区别,一个类名,后跟一个或多个需要从其中派生的父类:

class SubClassName (ParentClass1[, ParentClass2, ...]):

    'optional class documentation string'

    class_suite

实例
class Parent(object): # define parent class 定义父类

    def parentMethod(self):

    print 'calling parent method'
class Child(Parent): # define child class 定义子类

    def childMethod(self):

    print 'calling child method'

继承与覆盖

继承

不同于Java,python的子类继承父类后,会把父类的所有的方法,包括构造器init()也继承下来.

class Parent():

    def __init__(self):

        print "init Parent class instance"
    def func(self):

        print "call parent func"
class Child(Parent):

    def __init__(self):

        print "init Child class instance"
child = Child()

child.func()

输出
init Child class instance 

call parent func

super关键字

super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。语法如下

super(type[, obj])

示例
class C(B):

    def method(self, arg):

        super(C, self).method(arg)

注意

super继承只能用于新式类,用于经典类时就会报错。
新式类:必须有继承的类,如果没什么想继承的,那就继承object
经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』
实例

class Parent(object):

    def __init__(self):

        self.phone = '123456'

        self.address = 'abcd'
class Child(Parent):

    def __init__(self):

        super(Child, self).__init__()

        self.data = 100
def main():

    child = Child()

    print "phone is: ", child.phone

    print "address is: ", child.address

    print "data is: ", child.data
if __name__ == '__main__':

    main()

输出
phone is:  123456

address is:  abcd

data is:  100

重写

子类只要重新定义一个与父类的方法同名的方法,就可以重写覆盖父类的方法. 子类只要把上例父类的func(self)重写就行了.

class Parent():

def __init__(self):

print "init Parent class instance"

def func(self):

print "call parent func"

class Child(Parent):

def __init__(self):

print "init Child class instance"
child = Child()

child.func()

输出
init Child class instance

call Child func

多重继承

同 C++一样,Python 允许子类继承多个基类。但一般不推荐用多重继承.语法如下:

class Father():

    def __init__(self):

        print "init Father instance"
class Mother():

    def __init__(self):

        print "init Mother instance"
class Child(Father, Mother):

    pass

类、实例和其他对象的内建函数

issubclass()

布尔函数判断一个类是另一个类的子类或子孙类。它有如下语法:

issubclass(sub, sup)

isinstance()

布尔函数在判定一个对象是否是另一个给定类的实例时,非常有用。它有如下语法:

isinstance(obj1, obj2)

attr()系列函数

●hasattr()
它的目的就是为了决定一个对象是否有一个特定的属性,一般用于访问某属性前先作一下检查。
●getattr()和setattr()
●getattr()和 setattr()函数相应地取得和赋值给对象的属性,

●delattr()
删除特定的属性

实例

class Child(Parent):

    def __init__(self):

        self.data = 100
child = Child()

print "has data attr?", hasattr(child, 'data')
print "delete attr"

delattr(child, 'data')
print "has data attr?", hasattr(child, 'data')
print "set data attr to 200"

setattr(child, 'data', 200)

print "data attr is: ", getattr(child, 'data')

输出
has data attr? True

delete attr

has data attr? False

set data attr to 200

data attr is:  200

私有化

Python没有像Java那样实现真正的封装,只是用双划线和单划线实现私有化.

●双划线
防止外部访问.如在func前加双划线,可以防止包括子类的实例的访问.

    def __func(self):

        print "call"

●单划线
防止模块的属性用“from mymodule import *”来加载。
Python 相关文章推荐
python中的五种异常处理机制介绍
Sep 02 Python
Selenium(Python web测试工具)基本用法详解
Aug 10 Python
Python/ArcPy遍历指定目录中的MDB文件方法
Oct 27 Python
python实现Dijkstra静态寻路算法
Jan 17 Python
在numpy矩阵中令小于0的元素改为0的实例
Jan 26 Python
python实现全盘扫描搜索功能的方法
Feb 14 Python
Python学习笔记之自定义函数用法详解
Jun 08 Python
将python2.7添加进64位系统的注册表方式
Nov 20 Python
通过python实现windows桌面截图代码实例
Jan 17 Python
Python用类实现扑克牌发牌的示例代码
Jun 01 Python
如何基于Python按行合并两个txt
Nov 03 Python
python实现按日期归档文件
Jan 30 Python
简单介绍利用TK在Python下进行GUI编程的教程
Apr 13 #Python
Python中的面向对象编程详解(上)
Apr 13 #Python
进一步理解Python中的函数编程
Apr 13 #Python
Python中的异常处理简明介绍
Apr 13 #Python
python中的装饰器详解
Apr 13 #Python
Python生成器(Generator)详解
Apr 13 #Python
Python中函数的多种格式和使用实例及小技巧
Apr 13 #Python
You might like
全国FM电台频率大全 - 2 天津市
2020/03/11 无线电
网络资源
2006/10/09 PHP
检查php文件中是否含有bom的函数
2012/05/31 PHP
php定时计划任务的实现方法详解
2013/06/06 PHP
php获取服务器端mac和客户端mac的地址支持WIN/LINUX
2014/05/15 PHP
js单词形式的运算符
2014/05/06 Javascript
node.js中的fs.fchownSync方法使用说明
2014/12/16 Javascript
JS中产生标识符方式的演变
2015/06/12 Javascript
Javascript中String的常用方法实例分析
2015/06/13 Javascript
jQuery基于$.ajax设置移动端click超时处理方法
2016/05/14 Javascript
Vue2.0利用 v-model 实现组件props双向绑定的优美解决方案
2017/03/13 Javascript
详解react使用react-bootstrap当轮子造车
2017/08/15 Javascript
JavaScript 通过Ajax 动态加载CheckBox复选框
2017/08/31 Javascript
详解Angular6学习笔记之主从组件
2018/09/05 Javascript
JavaScript代码压缩工具UglifyJS和Google Closure Compiler的基本用法
2020/04/13 Javascript
[04:00]黄浦江畔,再会英雄——完美世界DOTA2 TI9应援视频
2019/07/31 DOTA
Python with的用法
2014/08/22 Python
python实现数据导出到excel的示例--普通格式
2018/05/03 Python
python中pip的安装与使用教程
2018/08/10 Python
Selenium的使用详解
2018/10/19 Python
Python实现将多个空格换为一个空格.md的方法
2018/12/20 Python
python编写微信公众号首图思路详解
2019/12/13 Python
Python线程协作threading.Condition实现过程解析
2020/03/12 Python
Python的轻量级ORM框架peewee使用教程
2021/02/05 Python
python中Pexpect的工作流程实例讲解
2021/03/02 Python
肯尼亚网上商城:Kilimall
2016/08/20 全球购物
Ruby中的保护方法和私有方法与一般面向对象程序设计语言的一样吗
2013/05/01 面试题
二年级语文教学反思
2014/02/02 职场文书
思想品德课教学反思
2014/02/10 职场文书
ktv好的活动方案
2014/08/17 职场文书
个人主要事迹材料
2014/08/26 职场文书
先进基层党组织事迹材料
2014/12/25 职场文书
外贸英文求职信范文
2015/03/19 职场文书
死磕 java同步系列之synchronized解析
2021/06/28 Java/Android
Java日常练习题,每天进步一点点(38)
2021/07/26 Java/Android
bootstrapv4轮播图去除两侧阴影及线框的方法
2022/02/15 HTML / CSS