對此可能有一個非常明顯的解決方案,但我是 python 的新手并且找不到它。我正在為我正在進行的練習專案制定一些系統,但我似乎無法讓它發揮作用:
class Item:
def __init__(self,name,description,type,mindamage,maxdamage):
self.name = name
self.desc = description
self.type = type
self.mindmg = mindamage
self.maxdmg = maxdamage
woodsman = Item("'Woodsman'","An automatic chambered in .22lr","gun",4,10)
inspect = input("inspect:").lower()
print(inspect .name)
print(inspect .desc)
print(inspect .type)
由于某種原因,我找不到解決方案。
uj5u.com熱心網友回復:
使用資料類和專案字典:
from dataclasses import dataclass
@dataclass
class Item:
name: str
description: str
item_type: str # don't use 'type' for variables name, it's reserved name
min_damage: int
max_damage: int
woodsman = Item(
name="'Woodsman'",
description="An automatic chambered in .22lr",
item_type="gun",
min_damage=4,
max_damage=10
)
# other items...
items = {
"woodsman": woodsman,
# other items...
}
inspect = items.get(input("inspect:").lower())
print(inspect.name)
print(inspect.description)
print(inspect.item_type)
uj5u.com熱心網友回復:
這可能更接近您想要做的事情:
inventory = {
"woodsman": Item("'Woodsman'","An automatic chambered in .22lr","gun",4,10)
}
inspect = inventory[input("inspect:").lower()]
print(inspect.name)
print(inspect.desc)
print(inspect.type)
請注意,您可能希望進行某種錯誤處理,以防用戶輸入inventory.
uj5u.com熱心網友回復:
我在擺弄并找到了另一個適合我的解決方案:
inspect = input("inspect:").lower()
exec("print(" inspect ".name)")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361616.html
標籤:Python
