新式类vs经典类,类的多态实现



```# 
# 经典类VS新式类
class person(object): #这就是新式类
    pass
    #super(Teacher,self).__init__(name,age,sex) # 新式类写法

class Person: #这就是经典类
    pass
    #School.__init__(self,name,age,sex) #经典类写法

## 新式类(先从左往右找,B没有就找C,C没有就找A!这种查询叫广度查询,先查完B,C这一层,再去查A层)
class A(object):
    def __init__(self):
        self.n="A"

class B(A):
    pass
    #def __init__(self):
    #self.n="B"

class C(A):
    def __init__(self):
        self.n="C"

class D(B,C):
    pass
    # def __init__(self):
    #     self.n="D"
d=D()
print(d.n)

## 经典类(经典类在python2中先找B,B没有就去找A!这叫深度查询,如果A里没找到就去找C)(新式类和经典类在pythin3中都是广度查询!)
class A:
    def __init__(self):
        self.n="A"

class B(A):
    #pass
    #def __init__(self):
       #self.n="B"

class C(A):
   #pass
    def __init__(self):
        self.n="C"

class D(B,C):
    pass
    #def __init__(self):
    #self.n="D"
d=D()
print(d.n)

# 多态
class Animal(object):
    def __init__(self, name):  # Constructor of the class
        self.name = name

    def talk(self):  # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self): #重新定义talk
        print('%s: 喵喵喵!' % self.name)

class Dog(Animal):
    def talk(self): #重新定义talk
        print('%s: 汪!汪!汪!' % self.name)

def func(obj):  # 一个接口,多种形态(传入不同的实例,调用的接口都是talk,单表达方式不同)
    obj.talk()

c1 = Cat('小晴')
d1 = Dog('李磊')
func(c1)
func(d1)

网站名称:新式类vs经典类,类的多态实现
网站链接:http://hbruida.cn/article/gpgegc.html