Home > front end >  How to convert string on variable in class?
How to convert string on variable in class?

Time:05-09

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?

CodePudding user response:

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.")

CodePudding user response:

Alternatively, if you would still like to use the class, you can do

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")

Remember that get_attr is not a method and takes in the object as the first parameter

  • Related