如何使用字串訪問類中的變數?
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
我應該用什么來做到這一點?
uj5u.com熱心網友回復:
使用itemy字典:
product_name = input("Product Name")
print(f'{GameShop.itemy[product_name]}'
字典確實是GameShop您需要的課程的唯一部分;我建議甚至不要GameShop上課,而只是制作一個作為商品名稱和價格真實來源的字典:
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.")
uj5u.com熱心網友回復:
或者,如果您仍想使用該課程,您可以這樣做
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 不是方法,而是將物件作為第一個引數
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470241.html
下一篇:如何在熊貓子集中參考自我
