• 技术文章 >常见问题 >Python常见问题

    python能重写方法吗

    (*-*)浩(*-*)浩2019-08-29 15:47:57原创2413

    方法重写

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

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    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__())

    专题推荐:python
    上一篇:python如何画直方图 下一篇:python如何打印列表长度

    相关文章推荐

    • 怎么启动运行python

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网