【问题标题】:Return dictionary from python class从 python 类返回字典
【发布时间】:2020-05-22 05:12:47
【问题描述】:

我查看了这个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() 被调用,有什么想法返回字典值吗?

【问题讨论】:

  • 你所做的只是设置一堆局部变量和/或任意属性self._dict。如果您希望数据成为实例的一部分,则需要修改 self。例如。 self['foo'] = 'bar'.
  • init 函数是一个构造函数,如果你想从你的类中返回一个字典,它不会返回任何东西,就像“hi._dict”一样使用它

标签: python python-3.x class dictionary


【解决方案1】:

hi 是一个变量,指向你的类HeaderInfo 的一个实例——它不是你的类的内部字典self._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())

查看您的成员字典中的内容。

如果您想在自己的类中存储内容,请更改您的添加方法

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

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多