主要想总结一下python的深度优先和广度优先
首先Python中分为经典类和新式类:
经典类: class A():
pass
新式类: class A(object):
pass
所以经典类和新式类的区别就是,在声明类的时候,新式类需要加上object关键字。
Python中经典类和新式类的区别主要体现在继承上:
Python的类如果继承了多个类,那么其寻找方法的方式有两种
- 当类是经典类时,多继承情况下,会按照深度优先方式查找
- 当类是新式类时,多继承情况下,会按照广度优先方式查找
注意!敲黑板!上面说的都是python2,只有在python2才区分经典类和新式类,而在ptyhon3中无论是否继承object,都默认继承object(如果一个类没有指定继承的父类),即python3中所有类均为新式类,所以在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()
sample 和sample2 继承类的顺序不同,所以结果也不同,按照从左到右的顺序来实现