Search code examples
pythonstringobjectinstantiationusing

Instantiate an object using a string as its name in Python


As it stands, I'm reading lines from a file to create "Monster" objects with certain int and string variables for each object. Every 2 lines creates a single object: one for strings, one for integers. Example file:

Slime,Slime ball
4,0,2,1,5,6,1
Pig,Pig skin
6,1,3,2,6,4,1

Here's my code to read from the file:

def read_from_file(file_name):
file = open(file_name)
monster_list = []
line_type = 1 #1=Monster Name, 2=Monster values
for each_line in file:
    if line_type == 1:
        #initialize the monster name
        value_list = each_line.split(",")
        name, trophy = value_list #name = first element, trophy = 2nd element
        line_type = 2
    else:
        if line_type == 2:
            #read values for monster values
            value_list = each_line.split(",") #now ['4','5',...]
            value_list = [int(e) for e in value_list] #now [1,2,3...]
            hp,shield,ap,mod,exp,gold,trophy_count = value_list
            line_type = 1
        monster_list.append(Monster(name, hp, shield, ap, mod, exp, gold, trophy, trophy_count))
#monster(monster_name)
file.close() #Close the file
return monster_list

Is there a way to alter the monster_list.append(...) line to use the name variable to instantiate a Monster object of the name? I.e.,

name = Monster(name, hp, shield, ap, mod, exp, gold, trophy, trophy_count)
monster_list.append(name)

Is this possible, or is there a similar way to accomplish this?


Solution

  • As far as I know, there is no way to do this. The reason being (again as far as I know) that there is no practical use for this.

    Might I inquire what you would like to accomplish by doing this? Even if it would be possible, I have a feeling there are easier ways to get the result you are trying to achieve...

    EDIT:

    From your comment I would say you should be using a dictionary instead of a list. This would allow you to do the following:

    monster_dict[name] = Monster(name, hp, shield, ap, mod, exp, gold, trophy, trophy_count))
    

    Subsequently, in the function that calls 'read_from_file', you will be able to retrieve each monster by it's name from the dict:

    slime = monster_dict['Slime']