Home > Software engineering >  How do I use variables with classes for python?
How do I use variables with classes for python?

Time:11-21

There is probably an stupidly obvious solution to this but I'm new to python and can't find it. I'm working out a few of the systems for a practice project I'm working on and I can't seem to get this to work:

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)

I can't find a solution to this for some reason.

CodePudding user response:

Use dataclasses and items dict:

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)

CodePudding user response:

This might be closer to what you're trying to do:

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)

Note that you will probably want to have some kind of error handling in case the user enters an item that doesn't exist in the inventory.

CodePudding user response:

I was fiddling around and found another solution that works for me:

inspect = input("inspect:").lower()
exec("print("   inspect   ".name)")
  • Related