覆盖关键的基本方法,同时保留其功能而不会使我的代码发臭

问题描述

在Godot中,可以定义一个信号并将其发送到一个方法中,该方法调用与其连接的所有方法。在此示例中,on_met_customer()连接到Merchant类中的signal met_customer,负责检测客户。

# Parent class
extends Merchant
class_name Salesman

func greet():
    print("Hello!")

func on_met_customer():
    greet
# Child class
extends Salesman
class_name CarSalesman

func shake_hands():
    print("*handshake*")
    
func on_met_customer():
    # .on_met_customer() I don't want to have to remember to call super
    shake_hands()
# Desired console output when calling on_met_customer() from the child class
Hello!
*handshake*

我想做的是:

  1. “扩展”而不是覆盖on_met_customer()以保留父功能而不调用super,或者:
  2. 在重写on_met_customer()时要以某种方式警告自己,不要忘了调用super

解决方法

给父母打电话是一种习惯;实际上,(在大多数情况下)可以选择。

如果您真的不想调用父方法,则可以选择在Merchant中添加自己的可覆盖方法:

extends Merchant
class_name Salesman

func greet():
    print("Hello!")

func meet_customer():
    pass  # override me

func on_met_customer():
    greet()
    meet_customer()
    rob_customer()
    # …

,然后在子级中覆盖它:

extends Salesman
class_name CarSalesman

func shake_hands():
    print("*handshake*")
    
func meet_customer():
    shake_hands()