【问题标题】:How do I use variables with classes for python?如何在 python 的类中使用变量?
【发布时间】:2021-11-22 00:57:33
【问题描述】:

这可能有一个愚蠢的明显解决方案,但我是 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)

由于某种原因,我找不到解决方案。

【问题讨论】:

  • 您得到的输入是一个字符串,它没有您要求的属性。另外,我很困惑,你想用这个程序做什么?
  • "cant get it to work" on stack overflow 它对您提供详细信息很有用:会发生什么?你希望发生什么?
  • 虽然inspect和.name(等)之间有空格,但inspect也是一个字符串,没有name属性,你的意思是woodsman.name(等)吗?
  • 从您的代码中看不出您要做什么。你正在提示用户输入——你想用它做什么?他们可能会输入哪些类型的内容,您想针对inspect 的这些不同值做些什么?
  • 只是一个建议——除非你想使用它,否则请不要在你的代码中使用 type。 (stackoverflow.com/questions/10568087/…)

标签: python


【解决方案1】:

使用dataclasses 和项目字典:

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)

【讨论】:

    【解决方案2】:

    这可能更接近你想要做的:

    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 中不存在的项目,您可能希望进行某种错误处理。

    【讨论】:

    • 您可能还想将属性名称“type”更改为其他名称。
    【解决方案3】:

    我一直在摆弄,找到了另一个适合我的解决方案:

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

    【讨论】:

    • 必须知道这有很多不好的编码习惯,对吧?另外,这绝对是我在此页面上看到的最模糊的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2015-07-23
    • 2011-10-04
    相关资源
    最近更新 更多