python新式类和经典类的区别

来源:互联网 发布:东方财富mac版 编辑:程序博客网 时间:2024/05/01 19:20

1.新式类对象可以直接通过__class__属性获取自身类型:type

2.继承搜索的顺序发生了改变,经典类多继承属性搜索顺序: 先深入继承树左侧,再返回,开始找右侧;新式类多继承属性搜索顺序: 先水平搜索,然后再向上移动

#经典类
class A:    def __init__(self):        print 'This is A'    def save(self):        print 'save method from A'class B (A):    def __init__(self):        print 'this is B'class C (A):    def __init__(self):        print 'this is C'    def save(self):        print 'save mothod from C'class D(B,C):    def __init__(self):        print 'this is D'd=D()d.save()
运行结果为:
this is Dsave method from A
经典类的搜索顺序是D->B->A,一种深度优先查找方式
#新式类
class A(object):    def __init__(self):        print 'This is A'    def save(self):        print 'save method from A'class B (A):    def __init__(self):        print 'this is B'class C (A):    def __init__(self):        print 'this is C'    def save(self):        print 'save mothod from C'class D(B,C):    def __init__(self):        print 'this is D'd=D()d.save()
运行结果为:
this is Dsave mothod from C
新式类的搜索顺序是D->B->C->A,一种广度优先查找方式

3.新式类增加了__slots__内置属性, 可以把实例属性的种类锁定到__slots__规定的范围之中
# -*- coding: utf-8 -*-
class Student(object):    __slots__ = ('name', 'age')   #只允许Student拥有name和age属性    def __init__(self):        self.name='张三'        self.age=20        self.sex='男'student=Student()
运行结果:
AttributeError: 'Student' object has no attribute 'sex'
报错
4.新式类增加了__getattribute__方法
Python 2.x中默认都是经典类,只有显式继承了object才是新式类Python 3.x中默认都是新式类,不必显式的继承object





0 0
原创粉丝点击