从python类返回字典

2024-10-04 01:29:06 发布

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

我查看了这个example并试图编写一个包含头信息的类。 从另一个类中,我会调用这个类并获取字典以供使用

# -*- 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)

当我尝试打印语句时,数据是打印的,但是

hi = HeaderInfo()

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

如果调用HeaderInfo(),是否可以返回dict值


Tags: importselfaddasciibytedictfileheader
1条回答
网友
1楼 · 发布于 2024-10-04 01:29:06

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

相关问题 更多 >