python中的新式类与经典类对比

2019-01-18  本文已影响19人  CurryCoder

1.经典类是直接声明的。使用dir()方法也可以看出新式类中定义很多新的属性和方法,而经典类就3个

class A:
    def __init__(self):
        pass
dir(A)
['__doc__', '__init__', '__module__']

2.新式类是在创建的时候继承内置object对象(或者是从内置类型,如list,dict等)

class B(object):
    def __init__(self):
        pass
dir(B)
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']

3. python2.7下经典类搜索顺序-----深度优先顺序

class A:
    def __init__(self):
        pass
    def save(self):
        print("This is from A")
        
        
class B(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from B")

class C(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from C")

class D(B, C):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from D")

d = D()
d.save()
This is from B
print('-------------------------------------这是分隔线---------------------------')
class A:
    def __init__(self):
        pass
    def save(self):
        print("This is from A")
        
        
class B(A):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from B")

class C(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from C")

class D(B, C):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from D")

d = D()
d.save()
This is from A

4. Python2.7下新式类搜索顺序-----广度优先顺序

class A(object):
    def __init__(self):
        pass
    def save(self):
        print("This is from A")

class B(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from B")

class C(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from C")

class D(B, C):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from D")
        
d = D()
d.save()
This is from B
print('-------------------------------------这是分隔线---------------------------')
class A(object):
    def __init__(self):
        pass
    def save(self):
        print("This is from A")

class B(A):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from B")

class C(A):
    def __init__(self):
        pass
    def save(self):
        print("This is from C")

class D(B, C):
    def __init__(self):
        pass
#     def save(self):
#         print("This is from D")
        
d = D()
d.save()
This is from C
上一篇下一篇

猜你喜欢

热点阅读