python - 使用文本文件创建一个继承自 dict 的类 - python

标签 python class object dictionary

我有这样一个文件:

1 23
2 21
5 23
561 2
73 19781

有了这个函数:

def readx(x):
    return {int(line.split()[0]):int(line.split()[1]) for line in x.split('\n')}

我可以得到这个:

{1: 23, 2: 21, 5: 23, 73: 19781, 561: 2}

但我需要将它放入某种类对象中,所以我尝试了这个:

z = """1 23
2 21
5 23
561 2
73 19781"""

def readx(x):
    return {int(line.split()[0]):int(line.split()[1]) for line in x.split('\n')}


class Foo(dict):
    def __init__(self, x):
        self = readx(x)

f = Foo(z)
print f

但它返回一个 None 而不是字典。

  1. readx() 是否有更 pythonic 的方法?它现在有点难看。
  2. 如何让类对象工作并使 foo 成为带有键和值的字典?

最佳答案

使用super :

class Foo(dict):
    def __init__(self, x):
        super(Foo, self).__init__(readx(x))

这将对数据调用 dict 构造函数,将其复制到对象中。

请注意,这也适用于 Python 3。

关于python - 使用文本文件创建一个继承自 dict 的类 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26055036/

相关文章:

python - 用另一个具有重复索引的数据框更新数据框

python - 信号问题 - 插槽,aboutToQuit()

java - 需要帮助访问嵌入式类中的信息

Python - 类型错误 : 'int' object is not callable

javascript - 将 javascript 数组分配给具有属性名称的 JSON 对象列表?

python - 在不使用内置函数的情况下返回第 n 个最小的数字 - Python

python - 处理 3D 体素数据的最佳方法是什么?

javascript - 即使在覆盖 module.exports 之后,模块仍然是一个空对象

c++ - 在堆栈和堆上创建对象数组

java - Java运行时如何获取变量声明的类型?