You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python函数中获取列表并正确打印英雄角色属性?

解决函数内列表访问与角色属性整合问题

为什么print(start.Hstats)无法工作?

Hstats是start函数内部的局部变量,不属于函数对象的属性。函数执行完毕后,局部变量会被销毁(除非显式保留),所以直接通过start.Hstats访问是无效的。

方法1:从函数返回列表(推荐)

这是最规范的做法,将函数内创建的列表作为返回值,在外部接收后即可使用:

def start():
    # 直接创建英雄属性列表
    Hstats = ["无名英雄", 100, 15, 5]
    return Hstats

# 调用函数并接收返回的列表
hero_stats = start()
print(hero_stats)  # 输出: ['无名英雄', 100, 15, 5]

方法2:整合Hero类属性到列表

如果用类来管理英雄属性,只需在函数内创建类实例,提取属性构建列表后返回:

class Hero:
    def __init__(self, name, hp, attack, defense):
        self.name = name
        self.hp = hp
        self.attack = attack
        self.defense = defense

def start():
    # 创建Hero实例
    player_hero = Hero("Jules", 120, 20, 8)
    # 从实例属性构建Hstats列表
    Hstats = [player_hero.name, player_hero.hp, player_hero.attack, player_hero.defense]
    return Hstats

# 获取并打印整合后的属性列表
hero_stats = start()
print(hero_stats)  # 输出: ['Jules', 120, 20, 8]

不推荐的方法:使用全局变量或函数属性

虽然可以通过全局变量或给函数添加属性的方式实现,但会破坏函数的封装性,不建议在项目中使用:

全局变量方式

Hstats = []  # 定义全局变量

def start():
    global Hstats
    Hstats = ["全局英雄", 90, 12, 4]

start()
print(Hstats)  # 输出: ['全局英雄', 90, 12, 4]

函数属性方式

def start():
    start.Hstats = ["属性英雄", 110, 18, 6]

start()
print(start.Hstats)  # 输出: ['属性英雄', 110, 18, 6]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 08:30:37