ITPub博客

首页 > IT职业 > IT职场 > python能重写方法吗

python能重写方法吗

IT职场 作者:mex 时间:2021-09-11 10:33:22 0 删除 编辑

方法重写

基类(被继承的类)的成员都会被派生类(继承的新类)继承,当基类中的某个方法不完全适用于派生类时,就需要在派生类中重写父类的这个方法。

如下面的示例代码,基类中定义的harvest()方法,无论派生类是什么水果都显示"水果…",如果想要针对不同水果给出不同的提示,可以在派生类中重写harvest()方法。例如,在创建派生类Orange()时,重写harvest()方法如下:

class Fruit:
    color = '绿色'

    def harvest(self, color):
        print(f"水果是:{color}的!")
        print("水果已经收获...")
        print(f"水果原来是{Fruit.color}的!")


class Apple(Fruit):
    color = "红色"

    def __init__(self):
        print("我是苹果")


class Orange(Fruit):
    color = "橙色"

    def __init__(self):
        print("n我是橘子")

    def harvest(self, color):  # 重写harvest 
        print(f"橘子是:{color}的!")
        print("橘子已经收获...")
        print(f"橘子原来是{Fruit.color}的!")


apple = Apple()  # 实例化Apple()类
apple.harvest(apple.color)  # 在Apple()中调用harvest方法,并将Apple()的color变量传入
orange = Orange()
orange.harvest(orange.color)  # 在Orange()中调用harvest方法,并将Orange()的color变量传入

执行结果:
	我是苹果
	水果是:红色的!
	水果已经收获...
	水果原来是绿色的!
	
	我是橘子
	橘子是:橙色的!
	橘子已经收获...
	橘子原来是绿色的!

注意:如本类中和父类同时存在这个方法名称,将只会执行本类中的这个方法,不会调用父类的同名方法(包括__init__())

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3932/viewspace-2836609/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: django1和2的区别
请登录后发表评论 登录
全部评论

注册时间:2019-07-09

  • 博文量
    193
  • 访问量
    1886