继承:子类对父类属性和方法的共享。
为什么要有继承?假设我们常常需要一个类的属性与方法,如果使用继承就可以方便的完成这个工作。如果没有继承那么就会重复很多代码。
直接上代码讲解
#父类
class Bird(object):
have_feather =True
way_of_reproduction='egg'
def move(self,dx,dy):
position=[0,0]
position[0]=position[0]+dx
position[1]=position[1]+dy
return position
#子类鸡继承Bird
class chicken(Bird):
way_of_move='walk'
possible_in_KFC=True
#子类天鹅继承Bird
class Swan(Bird):
way_of_move='fly'
possible_in_KFC=False
summer = chicken()
print summer.have_feather
print 'after move:',summer.move(5,8)
我们可以看到使用鸡这个子类中没有写have_feather的属性和move的方法。但是子类却可以直接使用,这就是继承。