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

Dav*_*e B 6 python oop

我正在用 Python 编写棋盘游戏《大富翁》。《大富翁》拥有三种类型的土地供玩家购买:房产(如木板路)、铁路和公用事业。房产有 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
Run Code Online (Sandbox Code Playgroud)

我想做的是这样的:

    dictname = "dictionary to pull from"  # based on space_type
    PropertyName = Game.dictname  # except .dictname would be "dictionary to pull from"
Run Code Online (Sandbox Code Playgroud)

在Python中是否可以将变量的值作为要引用的属性的名称传递?我也很感激有人告诉我我的做法从根本上是错误的,并提出了更好的解决方法。

che*_*ner 5

您可以使用该getattr功能:

property_name = getattr(Game, dictname)
Run Code Online (Sandbox Code Playgroud)