1

I am trying to use object orientation to create a game. I want to be able to access rooms and run activities but only be able to run certain activities in each room. I have all the activities assigned to a Object and I want to use the variable that the player typed in to access the Objects' variables then print what they did in the room.

    if activitiesList[i] == choice2:
        convert = (activitiesList2[i + 1])
        convert = str(convert)
        print ('You', a.convert, 'in', a.name)

Convert gets the name of the activity from the list then I want it to tell the Object which variable it's looking for. Everything I have tried just results in the program looking for the attribute 'convert' in the Object. How do i get it to search for the attribute that the player chose?

4

3 回答 3

1

It's not entirely clear what you're asking, but I suspect you want getattr:

action = getattr(a, convert)
于 2012-11-26T10:08:21.773 回答
1

If you want to access an attribute dynamically, you can use the getattr() function:

try:
    value = getattr(a, attribute_name)
except AttributeError:
    # attribute not found
    pass

Alternatively, you can also provide a default value to be returned if the attribute does not exist, instead of an exception to be thrown:

value = getattr(a, attribute_name, default_value)
于 2012-11-26T10:08:49.107 回答
0

Have you tried using a dict instead of a list?

stuff_in_room = {'hammer': ...}
if action in stuff_in_room:
    # do something
else:
    # can't do that
于 2012-11-26T10:09:57.980 回答