Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string on variable in class?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading