【问题标题】:How to get python dictionary as an object with snmp OID as key如何以 snmp OID 为键获取 python 字典作为对象
【发布时间】:2017-08-24 05:28:29
【问题描述】:

我正在尝试传递一个字典,其中键为 SNMP OID,值作为字典,其中包含一些值:

d = {'1.3.6.1.6.3.1.1.5.1': {'text':"something","help":'somethingelse','param':1},
     '1.3.6.1.6.3.1.1.5.2':{'text':"something for this oid","help":'somethingelse_for this','param':2} ,
     and so on for other 1000 snmp OIDs }

现在我想将这个字典传递给一个类,将它转换为字典对象并获取详细信息

class Struct(object):
def __init__(self, adict):
    """Convert a dictionary to a class

    @param :adict Dictionary
    """
    self.__dict__.update(adict)
    for k, v in adict.items():
        if isinstance(v, dict):
            self.__dict__[k] = Struct(v)


s = Struct(d)
s.? (what should be given here)

应该用什么来代替?因为它是一个 OID,我不能在引号(“”)中给出,因为我需要传递属性? 如果我通过了,我会收到无效的语法错误

s.'1.3.6.1.6.3.1.1.5.1'
or
s.1.3.6.1.6.3.1.1.5.1

另外说,在传递 oid 属性(例如 s.some_oid)后,我会得到一个字典对象,但我希望它返回该 OID 的值以及字典对象。有可能做到吗?

意思是如果我通过 s.some_oid 我应该得到 ​​p>

{'text':"something","help":'somethingelse','param':1}

还有一个字典对象,当使用 s.some_oid_text 我应该得到 ​​p>

something

【问题讨论】:

    标签: python class dictionary


    【解决方案1】:

    您尚未为您的班级定义 getitem 函数。一旦定义了它,就可以将结构对象用作任何普通字典。此外,要将其中的项目作为 Dictionary 对象获取,您还需要在 Struct 类本身中创建一个函数。供您参考,我创建了函数“itemsAsDict()”。

    d = {'1.3.6.1.6.3.1.1.5.1':{'text':"something","help":'somethingelse','param':1}}
    
    class Struct(object):
    
        def __init__(self, adict):
            """Convert a dictionary to a class
    
            @param :adict Dictionary
            """
    
            self.__dict__.update(adict)
    
            for k, v in adict.items():
                if isinstance(v, dict):
                    self.__dict__[k] = Struct(v)
    
        def __getitem__(self,key):
            return self.__dict__[key]
    
        def values(self):
            return self.__dict__.values()
    
        def itemsAsDict(self):
            return dict(self.__dict__.items())
    
    
    s = Struct(d)
    
    
    #Get the dictionary at OID
    print s['1.3.6.1.6.3.1.1.5.1'].itemsAsDict()
    ##Output : {'text': 'something', 'help': 'somethingelse', 'param': 1}
    
    #Get the exact text
    print s['1.3.6.1.6.3.1.1.5.1']['text']
    ###Output : something
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多