擅长:python、mysql、java
<p>因为这是D&;D游戏,您可能也需要动态访问能力分数;例如,一个<code>saving_throw</code>方法可以使用您用来滚动<a href="https://roll20.net/compendium/dnd5e/Ability%20Scores#toc_35" rel="nofollow noreferrer">saving throw</a>的能力的名称。在这种情况下,使用字典而不是单独的属性通常是更好的设计:</p>
<pre class="lang-py prettyprint-override"><code>class Character:
def __init__(self):
self.abilities = { ability: roll_ability() for ability in abilities }
def get_ability_score(self, ability):
return self.abilities[ability]
def saving_throw(self, ability, bonus=0):
return roll_dice(20) + self.abilities[ability] + bonus
</code></pre>