Python and variable inside Variables

I have this object Troll. I made a random selection for his 'weapon'. Every time he appears his weapon will change. Under his object status section, I have a variable 'base_att' I want it to be the damage variable from his 'weapon' How can I have the base_att variable get updated by the 'weapon' variable random.choice note that I listed all my 'Weapons' in a different .PY file hence the items.weapon_for_troll calling.

class stick:
    name = 'Wooden Stick'
    damage = range (0,3)
    effect = None  

class rocks:
    name = 'Rocks'
    damage = range (0,5)
    effect = None

class troll:
    name = 'Troll'

class equipment:
    weapon = random.choice(items.weapon_for_troll)

class inventory:
    loot = None

class status:
    level = 1
    exp_point = 30
    hp_point = 30
    base_att = 
    base_def = 2
    bonus_def = 0

Upvotes: 0

Views: 62

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

You need to distinguis between ("static") class variables and ("non static") instance variables.

You are declaring all things static - thats great for things that are shared between all Trolls (like a "type" of monster - aka Troll) - not so great for things all "have" but are not "the same" - say like an inventory.

Try this approach:

import random

class Weapon: # no need to make each weapon its own class
    def __init__(self,name,damage,effect):
        self.name = name
        self.damage = damage
        self.effect = effect    

# create some troll weapons to choose from
troll_weapons = [ Weapon("Wooden Stick", range(3), None), Weapon("Rocks",range(5), None) ]

class Equipment:
    def __init__(self):
        # every time you instantiate a new equipment, generate a random weapon
        # for this instance you just created. They are not static, they differ
        # between each Troll (who instantiates its own Equipment)
        self.weapon = random.choice(troll_weapons)

class Troll:    
    name = 'Troll'
    def __init__(self):
        self.equipment = Equipment() # get a new instance of Eq for this troll
                                     # instance
        self.weapon = self.equipment.weapon  # "link" the troll weapon to its equipment
                                             # as shortcut - do smth similar to an 
                                             # instance of your "Stat" block

    def __str__(self):
        return f"Troll with: {self.weapon.name}"

# create a troll army
trolls = [Troll() for _ in range(10)]
for t in trolls:
    print(t)

Output:

Troll with: Rocks
Troll with: Wooden Stick
Troll with: Rocks
Troll with: Rocks
Troll with: Wooden Stick
Troll with: Rocks
Troll with: Wooden Stick
Troll with: Wooden Stick
Troll with: Wooden Stick
Troll with: Wooden Stick

Reads to check:

Classes
Class variables vs Instance variables

Sidenotes:

  • there are convention about naming schemes, classes start with a Capital, members lowercase

Upvotes: 1

Related Questions