Python: Reference an object attribute by variable

2019-03-01 00:33发布

问题:

This question already has an answer here:

  • How to access object attribute given string corresponding to name of that attribute 2 answers

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 have a variable purchase price and rents for 6 conditions (0-4 houses, or a hotel). Railroads and utilities have a fixed price and rents based on how many other railroads or utilities you own.

I have a Game() class that contains three dictionary attributes, all whose key is the land parcel's position on the board from 0-39:

  • .properties, whose values are a list containing the space's name, buy price, color group and rents (tuple);
  • .railroads, which consists only of the space name;
  • .utilities, also containing only the space name.

I did this because at certain points I want to iterate over the appropriate dictionary to see if the player owns other parcels of land in that dictionary; and also because the number of values differs.

Game() also has a tuple called space_types, where each value is a number representing a type of space (property, railroad, utility, luxury tax, GO, etc.). To find out what kind of space_type my player is sitting on:

space_type = space_types[boardposition]

I also have a Player() class with a method buy_property(), which contains a print statement that should say:

"You bought PropertyName for $400."

where PropertyName is the name of the space. But right now I have to use an if/elif/else block like so, which seems ugly:

    space_type = Game(space_types[board_position])
    if space_type is "property":
         # pull PropertyName from Game.properties
    elif space_type is "railroad":
         # pull PropertyName from Game.railroads
    elif space_type is "utility":
         # pull PropertyName from Game.utilities
    else:
         # error, something weird has happened

What I'd like to do is something like this:

    dictname = "dictionary to pull from"  # based on space_type
    PropertyName = Game.dictname  # except .dictname would be "dictionary to pull from"

Is it possible in Python to pass the value of a variable as the name of an attribute to be referenced? I will also appreciate someone telling me I'm approaching this fundamentally wrong and suggesting a better way to go about it.

回答1:

You can use the getattr function:

property_name = getattr(Game, dictname)


回答2:

Use the getattr built-in:

PropertyName = getattr(Game, dictname)

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



回答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]


标签: python oop