使用字典在Python中创建对象

2024-10-02 16:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

谢谢

    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)

Tags: the对象用户字典属性thatinitdef
1条回答
网友
1楼 · 发布于 2024-10-02 16:29:27

How could I make properties that were the keys and had properties that were the values?

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

如果您想将所有内容作为关键字argumrnet传递给__init__

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

相关问题 更多 >