Python:单继承&方法的重写

继承:让类和类之间转变为父子关系,子类默认继承父类的属性和方法

单继承:

class Person:
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Girl(Person):
    pass#占位符,代码里面类下面不写任何东西,会自动跳过,不会报错
girl=Girl()
girl.eat()

可以多个类是子类,就算子类自己没有,也可以使用父类的

继承的传递(多重继承):

class Father:#父类
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Son(Father):#Father类的子类
    pass#占位符,代码里面类下面不写任何东西,会自动跳过,不会报错
class Son1(Son):
    pass
son=Son()
son.eat()
son1=Son1()
son1.eat()##子类也可以继承父类的父类

方法的重写:

覆盖父类方法:

class Person:#父类
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Man(Person):#Person类的子类
    def eat(self):
        print("eat1")
man=Man()
man.eat()

继承父类的方法,子类增加自己的功能(对父类方法进行扩展):

第一种方法:

class Person:#父类
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Man(Person):#Person类的子类
    def eat(self):
        Person.eat(self)#************#
        print("eat1")
man=Man()
man.eat()

第二种方法(推荐使用,懒人写法):

super().方法名():super在Python里面是一个特殊的类

super():是使用super类创建出来的对象,可以调用父类中的方法:

class Person:#父类
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Man(Person):#Person类的子类
    def eat(self):
        #Person.eat(self)
        super().eat()
        print("eat1")
man=Man()
man.eat()

第三种方法:super(子类名,self).方法名():

class Person:#父类
    def eat(self):
        print("eat")
    def sing(self):
        print("sing")
class Man(Person):#Person类的子类
    def eat(self):
        #Person.eat(self)#************#
        #super().eat()#***********#
        super(Man,self).eat()
        print("eat1")
man=Man()
man.eat()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值