Dragoonknight Dragoonknight - 29 days ago 4x
Python Question

Python: How do I create effects that apply to variables in classes?

I am working on a text-based RPG, and I am trying to create magic spells that affect stats such as base attack, turn order, etc. I am using various classes for the spells in the format:

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

and I am calling the spells from a dictionary

bardSpells = {
1: BuffSpell(name= "Flare", level= 0, stat= baseAttack, value -1)

How would I use Flare on an enemy such as a goblin? I tried making a method

def useBuffSpell(target, spell):
target.spell.stat = target.spell.stat + spell.value

using parameters of

Additionally, what would be a good method of affecting next turn actions in a combat sequence via a spell?


Use getattr and setattr, and make the attribute reference in the spell a str:

bardSpells = {
    1: BuffSpell(name= "Flare", level= 0, stat="baseAttack", value -1)

def useBuffSpell(target, spell):
    setattr(target, spell.stat,
            getattr(target, spell.stat, 0) + spell.value)

setattr is a builtin that, given an object, the name of an attribute, and a value, sets that attribute of the object to the value. getattr is a builtin that, given an object, the name of an attribute, and optionally a default (0 in the above example), returns that attribute of the object, or the default if the object does not have an attribute by that name. If no default is given, nonexistent attribute access raises an AttributeError.

The above example, if you did useBuffSpell(goblin, bardSpells[1]), would reduce the goblins baseAttack by 1, or set it to -1 if it did not have a baseAttack.