实例变量与静态变量
本课属于 Coddy GDScript 学习旅程的“面向对象编程”单元。第 9 课,共 65 课。
类中的普通 var 是实例变量:每个对象都有自己的变量。static var 则属于类:它只有一个值,由所有对象共享。
# student.gd
class_name Student
extends RefCounted
static var school: String = "Godot High"
static var count: int = 0
var student_name: String
func _init(new_name: String) -> void:
student_name = new_name
count += 1var ada := Student.new("Ada")
var bo := Student.new("Bo")
print(Student.count) # 2
print(ada.student_name, " and ", bo.student_name) # Ada and Bo
Student.school = "Godot Academy"
print(ada.school) # Godot Academy
print(bo.school) # Godot Academy通过类名读取静态变量,例如 Student.count,无需创建对象。在类内部,使用类名:在 _init() 中执行 count += 1,即可统计到目前为止创建的所有学生。
修改 Student.school 会同时改变所有学生的学校。ada.school = "Night School" 也会产生同样的效果,因为只有一个 school;写出类名可以让这一点更清楚。
const 的共享方式相同,但它永远不能改变。对于程序运行期间会变化的共享数据,例如计数器或所有对象都遵循的设置,请使用 static var。
挑战
简单在 bank_account.gd 中完成 BankAccount 类:
- 一个静态
int变量interest_percent,初始值为2,由所有账户共享 - 一个静态
int变量account_count,初始值为0;每创建一个新账户,构造函数就将其加1 describe()返回HOLDER: $BALANCE at PERCENT%,使用账户的holder和balance,以及共享的interest_percent
提供的代码会读取后续账户的数量和每个账户的一行 holder balance,然后读取新的利率。它会输出 BankAccount.account_count 和每个账户,将 BankAccount.interest_percent 设置为新利率,然后再次输出每个账户。对于 Alice 1000、Bob 2000 和利率 3,输出为:
Accounts opened: 2
Alice: $1000 at 2%
Bob: $2000 at 2%
After the rate change:
Alice: $1000 at 3%
Bob: $2000 at 3%你的代码要写在 bank_account.gd 中。main.gd 包含提供的输入/输出代码,不能编辑。
亲手试试
extends Node
func _ready():
# 提供的输入和输出代码:保持原样
var accounts: Array[BankAccount] = []
var count := int(OS.read_string_from_stdin())
for i in count:
var parts := OS.read_string_from_stdin().split(" ")
accounts.append(BankAccount.new(parts[0], int(parts[1])))
print("Accounts opened: %d" % BankAccount.account_count)
for account in accounts:
print(account.describe())
BankAccount.interest_percent = int(OS.read_string_from_stdin())
print("After the rate change:")
for account in accounts:
print(account.describe())
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: GDScript 在线编译器