微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。