【问题标题】:Creating Objects in Python using a Dictionary使用字典在 Python 中创建对象
【发布时间】:2016-01-24 01:30:38
【问题描述】:

我正在编写一个允许用户创建类别的 python 代码,然后用他们想要的任意数量的对象填充这些类别。最后,我打印了所有内容并使用文件 I/O 创建了一个包含信息的文本文档。

因为用户可以输入尽可能多的类别和飞机,所以我无法控制类的 init 中的参数数量。我想创建一个字典,为作为字典键的 Airplane 对象创建属性,并为这些属性创建值作为值。我该怎么做?

谢谢。

    class Airplane:
        def __init__(self, dictionaryPerhaps):
            #How could I make properties that were the keys and had properties that were the values?
            pass

    def objectCreation(valuesOC, catagoriesOC):
        thePlanes = { }
        for each in catagoriesOC:
             thePlanes [each] = valuesOC[each]

        theAirplaneObject = Airplane(thePlanes)

【问题讨论】:

  • 你能提供一些示例输入和输出吗?
  • 你可以继承dict,你只需要担心实现你的类的具体功能

标签: python class dictionary


【解决方案1】:

我怎样才能创建作为键的属性和作为值的属性?

def __init__(self, dictonaryPerhaps):
    self.__dict__.update(dictionaryPerhaps)

如果您希望将所有内容作为关键字 argumrnets 传递给 __init__

def __init__(self, **kwargs):
    self.__dict__.update(**kwargs)

【讨论】:

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