我查看了这个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值
hi
是一个变量,指向类的实例HeaderInfo
-它不是类的内部字典self._dict
实际上,您有一个dict类,该类也有一个dict成员——您填充该成员,而不是该类本身
打印
hi
不会显示self._dict
中的内容,除非覆盖类的def __str__(self)
和def __repl__(self)
方法以自定义类的打印方式(通过自身/列表内部)要打印成员,请添加
给你的班级和使用
查看成员词典中的内容
如果要在类本身中存储内容,请更改add方法
相关问题 更多 >
编程相关推荐