-3

I want to use the return value with classes but I don't know how to make it automatic. Let's say I give enemy("e21") and it returns e21

I've tried replacing the return value with string but It didn't work with my class

# <-- means separate file (and they are imported)
def e_info(input1, monster):
    if input1 == "name":
        return monster.name
#
def enemy(input2):
    if input2 == "e1":
        return e1
    if input2 == "e2":
        return e2
#
print(2 * "\n" + e_info("name", m.enemy(enemy_info)))
#
class Enemy:

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

e1 = Enemy("Test1")
46f278
  • 1
  • 2
  • 3
    your question cannot be understood, what class? what are `e1` and `e2`? show small examples of their definition and of `input2` – Chris_Rands Jul 26 '19 at 15:46

1 Answers1

1

The usual way to do this is to make a dictionary that maps the strings to the values:

def func(input2):
    mapping = {
        "e1": e1,
        "e2": e2,
    }
    return mapping[input2]

But this assumes that all possible values of input2 are known in advance. If this isn't the case, and input2 can be any arbitrary value, then you'll have to use something like exec() as in @Victor's answer.

John Gordon
  • 29,573
  • 7
  • 33
  • 58