Skip to content Skip to sidebar Skip to footer

Python: Reference An Object Attribute By Variable Name?

I'm programming the board game Monopoly in Python. Monopoly has three types of land that the player can buy: properties (like Boardwalk), railroads, and utilities. Properties hav

Solution 1:

Use the getattr built-in:

PropertyName = getattr(Game, dictname)

http://docs.python.org/2/library/functions.html#getattr


Solution 2:

You can use the getattr function:

property_name = getattr(Game, dictname)

Solution 3:

How about a dictionary of dictionaries?

D= {"property": Game.properties, "railroad": Game.railroads, "utility": Game.utilities}
space_type = Game(space_types[board_position])
dictname = D[space_type]

Post a Comment for "Python: Reference An Object Attribute By Variable Name?"