从类访问特定值

我想从字典中访问特定值。 希望有人可以帮助我解决这个问题。 预先感谢。

我一直在编写自己的冒险游戏,我想为状态字典创建类和方法。

class state_dict(object):
    def __init__(self):
        pass

    def create_state_dict(self):
        hero_dict = {
            "name": "Hero","lvl": 1,"xp" : 0,"lvlnext" : 25,"stats" : {
                "str" : 1,"dex" : 1,"int" : 1,"hp" : 30,"atk" : [5,12]
            }
        }
        return(hero_dict)
a = state_dict()
print(a.create_state_dict())
michael2014 回答:从类访问特定值

字典常量的keys(不是values)是吗?如果是这样,这对于dataclass来说将是一个很好的用例。通常,dict包含许多对项目-键值对-每个项目都可以快速添加和取出。 dataclass是表示字段(类似于dict的“键”)的数据的一种方式,它是表示字段不变的事物的正确方法。无论如何,这是一种实现游戏角色的方法:

import dataclasses
from typing import List


@dataclasses.dataclass()
class CharacterStats:
    strength: int
    dexterity: int
    intelligence: int
    hitpoints: int
    attack: List[int]


@dataclasses.dataclass()
class GameCharacter:
    name: str
    level: int
    experience: int
    experience_required_for_next_level: int
    stats: CharacterStats

GameCharacter的实例化如下:

willy_the_wizard_stats = CharacterStats(
    strength=1,dexterity=1,intelligence=1,hitpoints=30,attack=[5,12]
)

willy_the_wizard = GameCharacter(
    name="Willy",level=1,experience=0,experience_required_for_next_level=25,stats=willy_the_wizard_stats
) 

要获取巫师威利的名字和力量的价值,请

willy_name = willy_the_wizard.name  # Willy
willy_strength = willy_the_wizard.stats.strength  # 1

编辑:我忘了提及的一件事是,通常,最好(1)不缩写变量名,(2)避免使用键,字段名等,任何名称与a相同的变量内置Python。 Here是内置列表。缩写可能不容易为他人所理解,并且容易拼错,从而导致错误。关于第(2)点,使用内置名称可能会导致错误,例如,想知道为什么像range(int(my_variable))这样的简单东西不起作用。

本文链接:https://www.f2er.com/3131526.html

大家都在问