You need to enable JavaScript to run this app. DSSL2使用class与struct实现开户功能代码运行问题求助
优惠活动
大模型
产品
解决方案
定价
更多

DSSL2使用class与struct实现开户功能代码运行问题求助

问题修正方案

首先纠正原始类/结构体的定义错误

你原来的代码把customer结构体错误缩进在了Account类的内部,属于作用域错误,先调整为独立定义:

class Account:
    let id
    let type
    let balance

    # Account(nat?, account_type?, num?) -> Account?
    # 构造指定ID、账户类型、余额的账户,余额不能为负
    def __init__(self, id, type, balance):
        if balance < 0: error('Account: negative balance')
        if not account_type?(type): error('Account: unknown type')
        self.id = id
        self.type = type
        self.balance = balance

# customer结构体独立定义,不要放在Account类内部
struct customer:
    let name
    let bank_account

原有代码错误点整理

  • 构造Account实例时传入了未定义的id、balance变量,此时这两个值还没有完成计算
  • 字段访问路径错误:customer结构体的账户字段名为bank_account,不是Account,不能用newacc.Account.xxx的格式访问
  • len调用语法错误:DSSL2中len是函数,用法为len(customers),不是属性调用len.customers
  • 重复赋值不可变字段:struct的let字段初始化后不可修改,不能先构造实例再修改字段值,必须先计算好所有参数再构造实例
  • 数组拼接语法错误:数组只能和另一个数组合并,不能直接加单个元素,需要把新元素包裹为数组[newacc]再拼接

修正后的open_account函数实现

def open_account(name, type, customers):
    # 先计算新账户的ID
    let new_id = 1
    if len(customers) > 0:
        new_id = customers[len(customers)-1].bank_account.id + 1
    # 先构造Account实例,再构造customer实例
    let new_account = Account(new_id, type, 0)
    let new_customer = customer(name, new_account)
    # 返回拼接后的新客户数组(如果要修改原数组可以改用customers.append(new_customer))
    return customers + [new_customer]

调试思路

  1. 先单独测试Account类的构造逻辑,传入合法/非法参数验证校验逻辑是否正常触发
  2. 测试空数组调用函数的场景,验证新ID是否从1开始生成
  3. 测试已有客户的数组调用场景,验证ID是否自增正确
  4. 打印返回的客户数组内容,确认每个字段的赋值符合预期

内容的提问来源于stack exchange,提问作者masonn99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 12:15:03