我有这样一个文件:
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 而不是字典。
readx()
是否有更 pythonic 的方法?它现在有点难看。- 如何让类对象工作并使
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/