Python:通过变量名称引用对象属性? [英] Python: Reference an object attribute by variable name?

查看:747
本文介绍了Python:通过变量名称引用对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写棋盘游戏Monopoly.垄断者可以购买三种类型的土地:财产(例如Boardwalk),铁路和公用事业.物业的可变购买价格和租金适用于6种情况(0-4栋房屋或一家酒店).铁路和公用事业的固定价格和租金取决于您拥有的其他铁路或公用事业的数量.

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.

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

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,其值是一个包含空间名称,购买价格,颜色组和租金(元组)的列表;
  • .railroads,仅由空间名称组成;
  • .utilities,也仅包含空间名称.

之所以这样做,是因为在某些时候,我想遍历相应的词典,以查看玩家是否在该词典中拥有其他土地.也因为值的数量不同.

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()还具有一个称为space_types的元组,其中每个值都是代表空间类型(财产,铁路,公用事业,奢侈品税,GO等)的数字.找出玩家坐在哪种space_type上:

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]

我还有一个Player()类,带有方法buy_property(),该类包含一条打印语句,内容应为:

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

"You bought PropertyName for $400."

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

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

我想做的是这样的:

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

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

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.

推荐答案

您可以使用getattr函数:

property_name = getattr(Game, dictname)

这篇关于Python:通过变量名称引用对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆