【问题标题】:Storing Class Arguments in a List将类参数存储在列表中
【发布时间】:2014-09-08 16:41:20
【问题描述】:

最近我一直在开发一个基于文本的游戏作为个人项目。没有真正的原因,只是为了它。我通常很流利地使用 Python(我已经完成了 CodeCademy 的全部 Python 课程并完成了自己的研究),但我遇到了一些我想确保在实施之前能够工作的东西。

本质上,是否可以将类的参数嵌套到列表中?

这是一个类似于我正在做的例子:

class Item(object):
    def __init__(self, name, weight):
         self.name = name
         self.weight = weight

tempDict = {
     'flashlight' = ['flashlight',5],
}

flashlight1 = Item(tempDict['flashlight'])

print flashlight1.name

这应该返回:

flashlight

我真的希望这会奏效。我有一个依赖于此工作的完整 ID 结构。如果没有,我该如何做类似的事情,以便我可以有一个规定的项目列表和基值,我可以分配给具有 ID 的特定项目?

提前致谢。

【问题讨论】:

    标签: python list class python-2.7 arguments


    【解决方案1】:

    如果你 unpack tempDict['flashlight']* 放在它前面,它将起作用:

    >>> class Item(object):
    ...     def __init__(self, name, weight):
    ...          self.name = name
    ...          self.weight = weight
    ...
    >>> tempDict = {
    ...      'flashlight' : ['flashlight',5],
    ... }
    >>> flashlight1 = Item(*tempDict['flashlight'])
    >>> print flashlight1.name
    flashlight
    >>> print flashlight1.weight
    5
    >>>
    

    在上面的演示中:

    flashlight1 = Item(*tempDict['flashlight'])
    

    相当于:

    flashlight1 = Item('flashlight', 5)
    

    【讨论】:

    • 非常感谢!这正是我想要的!
    【解决方案2】:

    如果您使用字典而不是列表来存储参数,您的参数字典会更加清晰:

    tempDict = {
        'flashlight': { 'name': 'flashlight', 'weight': 5 }
    }
    flashlight1 = Item(**tempDict['flashlight'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多