0

What I want to do is randomly choose an item in a list, and then use that to pull through the attributes of that object. I can obviously hard code the current_target variable (Creature.Dog.attr1 for example) but I would ideally like this to be generated.

My code goes like this:

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = ['Squirrel', 'Dog', 'Goblin']

def get_creature():
    return random.choice(creature_list)

These are called from my main class:

current_target = Creature.get_creature()
print("The current target is %s, and has %s, and %s"  
     % (current_target, Creature.current_target.attr1, Creature.current_target.attr2))

2 Answers 2

1

Use instances not strings

A simple change is to put your Creature instances in the list and choose from there.

import random

class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2


Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)

current_target = get_creature()
print("The current target is %s, and has %s, and %s"
     % (current_target.name, current_target.attr1, current_target.attr2))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Graeme. I had the Creature in the list before, but was still trying to call from the class rather then straight from the variable. That line to explain the change really helped for me.
1
class Creature(object):

    def __init__(self, name, attr1, attr2):
        self.name = name
        self.attr1 = attr1
        self.attr2 = attr2

Squirrel = Creature("Squirrel", 20, 1)
Dog = Creature("Dog", 50, 10)
Goblin = Creature("Goblin", 100, 100)

creature_list = [Squirrel, Dog, Goblin]

def get_creature():
    return random.choice(creature_list)
current_target = get_creature()
print("The current target is %s, and has %s, and %s"
 % (current_target.name, current_target.attr1, current_target.attr2))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.