Dragoonknight Dragoonknight - 27 days ago 5x
Python Question

Python: How do I refer to an attribute of a class by an attribute of another class or a variable?

I am trying to create a magic system in my text-based RPG that refers to an attribute of a monster class using the attribute from the magic class.
The monster class looks like

class monster(object):
def __init__(self, **kwargs):

with the list of monsters being store in the format

bestiary = {
99999: monster(name="Slime", currentHP= 3, maxHP= 10, initiativeMod= 1, AC= 0, baseAttack= 0, equippedWeapon= itemsList[13], speed = 10) ##Syntax items

The spells are created in the form

class BuffSpell(object):
def __init__(self, **kwargs):

with instances of each spell in the form

bardSpells = {
2: BuffSpell(name= "Flare", level= 0, stat= "baseAttack", value = -1, MP = 3, spellType = "buff"),

I am trying to refer to an attribute in monster that is given by an attribute in the spell like this

def useMagic(target, spell):
if spell.spellType == "buff":
x = spell.stat
target.x += spell.value

which of course doesn't work. How can I get the spell.stat attribute and apply spell.value to the corresponding attribute in monster?


You could try something like the following:

def use_magic(target, spell):
    if spell.spell_type == "buff":
        stat = spell.stat
        setattr(target, stat, getattr(target,stat) + spell.value)