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 do I use variables with classes for python?

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.

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

>Solution :

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