Python:通过变量名称引用对象属性?

时间:2013-06-12 01:40:59

标签: python oop

我正在用Python编写棋盘游戏Monopoly。垄断有三种类型的土地,玩家可以购买:财产(如Boardwalk),铁路和公用事业。物业具有可变的购买价格和6个条件(0-4房屋或酒店)的租金。铁路和公用事业的固定价格和租金取决于您拥有的其他铁路或公用设施。

我有一个Game()类,其中包含三个字典属性,所有关键字都是地块在0-39之间在地板上的位置:

  • .properties,其值为包含空间名称,购买价格,颜色组和租金(元组)的列表;
  • .railroads,仅包含空格名称;
  • .utilities,也只包含空格名称。

我之所以这样做,是因为在某些方面我想迭代相应的字典,看看该玩家是否拥有该字典中的其他土地;还因为值的数量不同。

Game()还有一个名为space_types的元组,其中每个值都是一个代表空间类型的数字(属性,铁路,公用事业,奢侈税,GO等)。要了解我的播放器所使用的space_type类型:

space_type = space_types[boardposition]

我还有一个带有方法buy_property()的Player()类,它包含一个应该说的打印语句:

"You bought PropertyName for $400."

其中PropertyName是空格的名称。但是现在我必须像这样使用if / elif / else块,这看起来很难看:

    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

我想做的是这样的事情:

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

在Python中是否可以将变量的值作为要引用的属性的名称传递?我也很感激有人告诉我,我正在接近这个根本错误,并建议一个更好的方法来解决它。

3 个答案:

答案 0 :(得分:3)

使用内置的getattr

PropertyName = getattr(Game, dictname)

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

答案 1 :(得分:2)

字典词典怎么样?

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

答案 2 :(得分:1)

您可以使用getattr功能:

property_name = getattr(Game, dictname)
相关问题