Python之 继承

1.继承

class People(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def eat(self):
        print("%s is eating..."%self.name)

class Man(People):
    def __init__(self,name,age,money,food):
        super(Man,self).__init__(name,age)  #继承People类的变量定义
        self.money=money
        self.food=food
    def run(self):
        print("%s have %s $"%(self.name,self.money))
   # def eat(self):
        print("%s is eating %s"%(self.name,self.food))

m1=Man("He Yuan",16,2800)
m1.eat()   #继承People类的eat方法
m1.run()   #子类新增功能

eg2.

class People(object):
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def eat(self):
        print("%s is eating..."%self.name)

class Man(People):
    def __init__(self,name,age,money,food):
        super(Man,self).__init__(name,age)  #继承People类的变量定义
        self.money=money
        self.food=food
    def run(self):
        print("%s have %s $"%(self.name,self.money))
    def eat(self):
        print("%s is eating %s"%(self.name,self.food))

m1=Man("He Yuan",16,2800,"baozi")
m1.eat()   #重写People类的eat方法
m1.run()   #子类新增功能

综上eg1,eg2,可得3条结论:1.,子类继承父类的所有功能。2.子类可新增自己特有的方法。3子类可把父类不适合的方法覆盖重写;

 

阅读更多
换一批

没有更多推荐了,返回首页