首页 > 文章列表 > python中重写与调用方法是什么

python中重写与调用方法是什么

Python 重写 调用
197 2022-08-07

重写父类方法与调用父类方法

1、重写父类方法

所谓重写,就是子类中,有一个和父类相同名字的方法,在子类中的方法会覆盖掉父类中同名的方法。

class Cat(object):
    def sayHello(self):
        print("Hello:Cat")
class Bosi(Cat):
    def sayHello(self):
        print("Hello:Bosi")
bs = Bosi()
bs.sayHello()

运行结果为:

Hello:Bosi

2、调用父类方法

重写之后,如果发现仍然需要父类方法,则可以强制调用父类方法。

class Cat(object):
    def __init__(self,name):
        self.name = name
        self.color = "黄色"
    
class Bosi(Cat):
    def __init__(self,name):
        #Cat.__init__(self,name) #python2的语法
        #调用父类的方法
        super().__init__(name)
        def getName(self):
            return self.name
        pass
bs = Bosi("波斯")
print(bs.name)
print(bs.color)

运行结果为:

波斯
黄色