如何转换 class 中变量的字符串?
How to convert string on variable in class?
如何使用字符串访问 class 中的变量?
class GameShop:
ManaPotion = "ManaPotion"
priceManaPotion = 50
HealthPotion = "HealthPotion"
priceHealthPotion = 50
StaminaPotion = "StaminaPotion"
priceStaminaPotion = 50
itemy = {
ManaPotion: priceManaPotion,
HealthPotion: priceHealthPotion,
StaminaPotion: priceStaminaPotion,
}
shop = GameShop
print(GameShop.priceHealthPotion)
product_name = input("Product Name")
print(f'{GameShop}' + '.price' + f'{product_name}' )
给出结果<class '__main__.GameShop'>.priceproductname
应该是:50
我应该用什么来做这个?
使用itemy
词典:
product_name = input("Product Name")
print(f'{GameShop.itemy[product_name]}'
字典确实是您需要的 GameShop
class 的唯一部分;我建议甚至不要将 GameShop
设为 class,而只是制作一个字典,这是商品名称和价格的真实来源:
shop_prices = {
"ManaPotion": 50,
"HealthPotion": 50,
"StaminaPotion": 50,
}
然后你可以像这样循环打印价格:
print("Shop prices:")
for item, price in shop_prices.items():
print(f"\t{item}: {price}")
并使用商品名称作为键在 shop_prices
中查找给定商品的价格:
item = input("What do you want to buy?")
try:
print(f"That'll be {shop_prices[item]} gold pieces, please.")
except KeyError:
print(f"Sorry, {item} isn't in this shop.")
或者,如果您仍想使用 class,您可以执行
try:
price=getattr(shop, f"price{product_name}")
print(f"The cost of {product_name} is {price}")
except AttributeError:
print("Sorry, this item is not available")
记住 get_attr 不是一个方法,它将对象作为第一个参数
如何使用字符串访问 class 中的变量?
class GameShop:
ManaPotion = "ManaPotion"
priceManaPotion = 50
HealthPotion = "HealthPotion"
priceHealthPotion = 50
StaminaPotion = "StaminaPotion"
priceStaminaPotion = 50
itemy = {
ManaPotion: priceManaPotion,
HealthPotion: priceHealthPotion,
StaminaPotion: priceStaminaPotion,
}
shop = GameShop
print(GameShop.priceHealthPotion)
product_name = input("Product Name")
print(f'{GameShop}' + '.price' + f'{product_name}' )
给出结果<class '__main__.GameShop'>.priceproductname
应该是:50
我应该用什么来做这个?
使用itemy
词典:
product_name = input("Product Name")
print(f'{GameShop.itemy[product_name]}'
字典确实是您需要的 GameShop
class 的唯一部分;我建议甚至不要将 GameShop
设为 class,而只是制作一个字典,这是商品名称和价格的真实来源:
shop_prices = {
"ManaPotion": 50,
"HealthPotion": 50,
"StaminaPotion": 50,
}
然后你可以像这样循环打印价格:
print("Shop prices:")
for item, price in shop_prices.items():
print(f"\t{item}: {price}")
并使用商品名称作为键在 shop_prices
中查找给定商品的价格:
item = input("What do you want to buy?")
try:
print(f"That'll be {shop_prices[item]} gold pieces, please.")
except KeyError:
print(f"Sorry, {item} isn't in this shop.")
或者,如果您仍想使用 class,您可以执行
try:
price=getattr(shop, f"price{product_name}")
print(f"The cost of {product_name} is {price}")
except AttributeError:
print("Sorry, this item is not available")
记住 get_attr 不是一个方法,它将对象作为第一个参数