python新式类和经典类的区别实例分析

作者:bronk 时间:2023-07-28 10:01:02 

本文实例讲述了python新式类和经典类的区别。分享给大家供大家参考,具体如下:

新式类就是  class person(object): 这种形式的, 从py2.2 开始出现的

新式类添加了:

__name__ is the attribute's name.
__doc__ is the attribute's docstring.
__get__(object) is a method that retrieves the attribute value from object.
__set__(object, value) sets the attribute on object to value.
__delete__(object, value) deletes the value attribute of object.

新式类的出现, 除了添加了大量方法以外, 还改变了经典类中一个多继承的bug, 因为其采用了广度优先的算法

Python 2.x中默认都是经典类,只有显式继承了object才是新式类
python 3.x中默认都是新式类,经典类被移除,不必显式的继承object

粘贴一段官网上的作者解释

python新式类和经典类的区别实例分析

是说经典类中如果都有save方法, C中重写了save() 方法,  那么寻找顺序是 D->B->A, 永远找不到C.save()

代码演示:


#!/usr/bin/env python3
#coding:utf-8
'''
 新式类和经典类的区别, 多继承代码演示

'''

class A:
 def __init__(self):
   print 'this is A'
 def save(self):
   print 'save method from A'

class B:
 def __init__(self):
   print 'this is B'

class C:
 def __init__(self):
   print 'this is c'
 def save(self):
   print 'save method from C'

class D(B, C):
 def __init__(self):
   print 'this is D'
d = D()
d.save()

结果显示

this is D
save method from C

注意:在python3 以后的版本中, 默认使用了新式类, 是不会成功的

另外: 经典类中所有的特性都是可读可写的, 新式类中的特性只读的, 想要修改需要添加 @Texing.setter

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

来源:https://www.cnblogs.com/wenbronk/p/7141224.html

标签:python,新式类,经典类
0
投稿

猜你喜欢

  • Mysql数据库的安全性问题释疑

    2009-02-26 16:20:00
  • python Task在协程调用实例讲解

    2021-06-28 21:39:32
  • JS仿iGoogle自定义首页模块拖拽特效的方法

    2024-04-22 22:36:37
  • 图片自适应宽度新解决方法

    2009-09-22 14:55:00
  • 如何使用Python的Requests包实现模拟登陆

    2022-10-07 03:12:26
  • python实现网站的模拟登录

    2022-09-25 23:33:56
  • asp如何定时执行约定的页面?

    2009-11-15 20:17:00
  • golang操作mongodb的方法

    2023-09-15 03:49:24
  • 微信小程序实现简单的select下拉框

    2024-04-17 10:23:52
  • 如何动态产生变量?

    2009-11-18 16:33:00
  • 通过代码实例了解Python3编程技巧

    2023-07-13 17:48:46
  • 解决idea打开窗口/tab过多导致隐藏的问题

    2022-12-29 10:45:42
  • JavaScript实现五子棋游戏的方法详解

    2024-04-30 10:11:54
  • [新手必看]15个asp编程常见问题解答

    2007-08-22 13:07:00
  • 用JS实现飞机大战小游戏

    2024-06-22 20:12:33
  • 在Pycharm中使用GitHub的方法步骤

    2021-04-27 04:46:48
  • np.ones的使用小结

    2021-05-20 06:55:34
  • Windows下的Python 3.6.1的下载与安装图文详解(适合32位和64位)

    2021-06-28 16:02:24
  • 设计72变——寻求banner制作的变化

    2009-11-12 12:56:00
  • Python利用reportlab实现制作pdf报告

    2023-10-25 05:26:36
  • asp之家 网络编程 m.aspxhome.com