Python深度优先与广度优先区别

扩展一下知识,整理了一下百度的汇总。

Python中分为经典类和新式类:
  经典类:
      class A():
        pass

  新式类:
      class A(object):
        pass

所以经典类和新式类的区别就是,在声明类的时候,新式类需要加上object关键字。

Python中经典类和新式类的区别:
  区别主要体现在继承上:
    Python的类可以继承多个类,Java和C#中则只能继承一个类
    Python的类如果继承了多个类,那么其寻找方法的方式有两种
        当类是经典类时,多继承情况下,会按照深度优先方式查找
        当类是新式类时,多继承情况下,会按照广度优先方式查找
1、只有在python2中才分新式类和经典类,python3中统一都是新式类
2、在python2中 没有显示继承的object类的类,以及该类的子类都是经典类
3、在python2中,显示的声明继承object的类,以及该类的子类都是新式类
4、在python3中,无论是否继承object,都默认 继承object,即python3中所有类均为新式类


提示:如果没有指定基类, python的类会默认继承object类, object是所有python类的基类。
所以说p3都是广度优先

class people:
    # 定义基本属性
    name = ''
    age = 0
    # 定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0

    # 定义构造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 说: 我 %d 岁。" % (self.name, self.age))


# 单继承示例
class student(people):
    grade = ''

    def __init__(self, n, a, w, g):
        # 调用父类的构函
        people.__init__(self, n, a, w)
        self.grade = g

    # 覆写父类的方法
    def speak(self):
        print("%s 说: 我 %d 岁了,我在读 %d 年级" % (self.name, self.age, self.grade))


# 另一个类,多重继承之前的准备
class speaker():
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("我叫 %s,我是一个演说家,我演讲的主题是 %s" % (self.name, self.topic))


# 多重继承
class sample(student,speaker):
    a = ''

    def __init__(self, n, a, w, g, t):
        student.__init__(self, n, a, w, g)
        speaker.__init__(self, n, t)
class sample2(speaker,student):
    a = ''

    def __init__(self, n, a, w, g, t):
        student.__init__(self, n, a, w, g)
        speaker.__init__(self, n, t)

test = sample("Tim", 25, 80, 4, "Python")
test.speak()  # 方法名同,默认调用的是在括号中排前地父类的方法
test2 = sample2("Tim", 25, 80, 4, "Python")
test2.speak()

结果

猜你喜欢

转载自blog.csdn.net/u013434475/article/details/86657548
今日推荐