繁体   English   中英

从 python 类返回字典

[英]Return dictionary from python class

我查看了这个示例并尝试编写一个包含标题信息的类。 从另一个班级,我会调用这个班级并获取要使用的字典。

# -*- coding: utf-8 -*-
import binascii
import codecs
from datetime import datetime
from collections import defaultdict

class HeaderInfo(dict, object):
    def __init__(self):
        header_dict = defaultdict(list) # This shall hold all the issues in the parsed file
        # super(HeaderInfo, self).__init__(file)

        self._object = "C:\Sample.log"
        file = open(self._object, "rb")

        self._dict = {}

        byte = file.read(4)
        logFileSize = int.from_bytes(byte, "little")
        header_dict = self.add('logFileSize', logFileSize)
        dict = self.add('logFileSize', logFileSize)

        # print((dict))

        byte = file.read(20)
        hexadecimal = binascii.hexlify(byte)
        header_dict = self.add('fileType', codecs.decode(hexadecimal, "hex").decode('ascii'))
        dict = self.add('fileType', codecs.decode(hexadecimal, "hex").decode('ascii'))

        # print((dict))

        byte = file.read(5)
        hexadecimal = binascii.hexlify(byte)
        header_dict = self.add('fileVersion', codecs.decode(hexadecimal, "hex").decode('ascii'))
        dict = self.add('fileVersion', codecs.decode(hexadecimal, "hex").decode('ascii'))

        # print((dict))

        byte = file.read(10)
        hexadecimal = binascii.hexlify(byte)
        header_dict = self.add('fileNumber', codecs.decode(hexadecimal, "hex").decode('ascii'))
        dict = self.add('fileNumber', codecs.decode(hexadecimal, "hex").decode('ascii'))



    def add(self, id, val):
        self._dict[id] = val
        return self._dict

# print the data    
hi = HeaderInfo()    

print(hi)

当我尝试使用打印语句时,数据被打印出来,但是

嗨 = HeaderInfo()

, 不会在“hi”中返回任何值。

如果 HeaderInfo() 被调用,有没有办法返回 dict 值?

hi是指向类HeaderInfo实例的变量 - 它不是类的内部字典self._dict

您本质上有一个 dict 类,它也有一个 dict成员 - 您填充该成员 - 而不是类本身。

打印hi不会显示您的self._dict ,除非您覆盖类的def __str__(self)def __repl__(self)方法来自定义您的类的打印方式(通过本身/内部列表)。

要打印成员,请添加

def Get_Data(self):  # or some other name
    return self._dict

到你的班级并使用

print(hi.Get_Data())

查看您的会员词典中的内容。

如果你想在你的类中存储东西,改变你的 add 方法

def add(self, id, val):
    self[id] = val             # store it inside yourself, not your member
    return self                # this is questionalbe - as is the whole method
                               # if you do not want to make it part of your public api

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM