python变量通过变量名访问_Python:通过变量名称引用对象属性?

1586010002-jmsa.png

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.

解决方案

You can use the getattr function:

property_name = getattr(Game, dictname)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值