13.继承

继承

类(存储为文件)可以继承

  • 一个全局的类
  • 另一类文件
  • 另一个类文件中的内部类。

不允许多重继承。

继承使用 extends 关键字:

# Inherit/extend a globally available class.
extends SomeClass

# Inherit/extend a named class file.
extends "somefile.gd"

# Inherit/extend an inner class in another file.
extends "somefile.gd".SomeInnerClass

To check if a given instance inherits from a given class, the is keyword can be used:

# Cache the enemy class.
const Enemy = preload("enemy.gd")

# [...]

# Use 'is' to check inheritance.
if (entity is Enemy):
    entity.apply_damage()

要调用*基类*中的函数(即当前类``extend``后的类),请在函数名前面加上``.``:

.basefunc(args)

这特别有用,因为扩展类中的函数会替换基类中同名的函数。所以如果你仍然想调用它们,你可以使用``.``,这就像其他语言中的``super``关键字一样:

func some_func(x):
    .some_func(x) # Calls same function on the parent class.

Class Constructor

在类实例化时调用的类构造函数名为“_init”。如前所述,父类的构造函数在继承类时被自动调用。所以通常不需要显式调用’ ‘ ._init() ‘ ‘。

Unlike the call of a regular function, like in the above example with .some_func, if the constructor from the inherited class takes arguments, they are passed like this:

func _init(args).(parent_args):
   pass

通过例子可以更好地解释这一点。假设我们有这样一个场景:

# State.gd (inherited class)
var entity = null
var message = null

func _init(e=null):
    entity = e

func enter(m):
    message = m


# Idle.gd (inheriting class)
extends "State.gd"

func _init(e=null, m=null).(e):
    # Do something with 'e'.
    message = m

这里有几件事需要记住:

  1. if the inherited class (State.gd) defines a _init constructor that takes arguments (e in this case), then the inheriting class (Idle.gdhas to define _init as well and pass appropriate parameters to _init from State.gd
  2. Idle.gd 可以有与基类 ``State.gd``不同数量的参数
  3. in the example above, e passed to the State.gd constructor is the same e passed in to Idle.gd
  4. if Idle.gd’s _init constructor takes 0 arguments, it still needs to pass some value to the State.gd base class even if it does nothing. Which brings us to the fact that you can pass literals in the base constructor as well, not just variables. Eg.:
# Idle.gd

func _init().(5):
    pass
posted @ 2018-12-30 13:42  宸少凌  阅读(185)  评论(0编辑  收藏  举报

万年以来谁著史,三千里外欲封侯