字典常量的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