您的位置:首页 > 编程语言 > Python开发

Python的两种继承方法

2018-01-05 11:07 387 查看
# 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: