how can i get access to variable in class using string?
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}' )
Give result <class '__main__.GameShop'>.priceproductname
Should be: 50
What i should use to do this?
>Solution :
Use the itemy dictionary:
product_name = input("Product Name")
print(f'{GameShop.itemy[product_name]}'
The dictionary is really the only part of the GameShop class that you need; I’d suggest not even making GameShop a class, and just making a dict that’s the source of truth for the item names and prices:
shop_prices = {
"ManaPotion": 50,
"HealthPotion": 50,
"StaminaPotion": 50,
}
Then you can print the prices with a loop like:
print("Shop prices:")
for item, price in shop_prices.items():
print(f"\t{item}: {price}")
and look up the price for a given item in shop_prices by using the item’s name as the key:
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.")