Python的两种继承方法

# class Animal:   #经典类
class Animal(object):  #新式类
    def __init__(self,name):
        self.name = name
    def eat(self,foot):
        print('can eat',foot)

class Relation(object):
    def make_friends(self,obj):
        print('%s is making friends with %s'%(self.name,obj.name))
class Dog(Animal,Relation): #如果它们都有构造函数,在继承顺序上就会先继承Animal的init构造函数
    # def __init__(self,age):    #这样直接就会覆盖父类的所有构造函数
    #     self.age = age
    #所以要这样
    def __init__(self,name,age):
        # Animal.__init__(self,name) #方法一 经典类的写法
        super(Dog,self).__init__(name) #方法二 这种方法比较好 新式类的写法
        self.age = age
    def run(self):
        print('Dog is run soon')
        print('%d'%self.age)
    # def eat(self):   #直接就将父类方法替换了
    #     print('dog is can eat')
    def eat(self,foot):
        Animal.eat(self,foot)  #这样就可以在父类方法里面添加方法
        print('The dog is can eat')

class Cat(Animal):
    def pashu(self):
        print('cat can pashu %s'%self.name)


dog = Dog('dog',10)
# dog.eat('面包')
# dog.run()

cat = Cat('cat')
# cat.pashu()

# 下面这个就是多继承,注意,这里的cat作为一个参数传进去了
# 其实很好理解
# dog继承了Relation,因此可以多继承
dog.make_friends(cat)



你可能感兴趣的:(Python的两种继承方法)