python - 将 python 的 dict 功能扩展到用户创建的类

标签 python dictionary extend

是否可以向用户创建的类添加字典功能?

即:

class Foo(object):
    def __init__(self, x, y):
       self.x
       self.y
    def __dict__(self):
       return {'x': self.x, 'y': self.y}

f = Foo()
dict(f) <-- throws TypeError: iteration over non-sequence

最佳答案

dict 构造函数需要映射或可迭代的键/值对作为参数,因此您的类需要实现映射协议(protocol)或可迭代。

以下是如何使用后一种方法的示例:

class Foo(object):
    def __init__(self, x, y):
       self.x = x
       self.y = y
    def __iter__(self):
       return vars(self).iteritems()

使用示例:

>>> dict(Foo(2, 3))
{'x': 2, 'y': 3}

不过我不知道这有什么用。你可以这样做

>>> vars(Foo(2, 3))
{'x': 2, 'y': 3}

无需在类上实现 __iter__() 即可工作。

关于python - 将 python 的 dict 功能扩展到用户创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8168957/

相关文章:

javascript - $.extend() = 与服务器循环一起使用时不扩展

api - 扩展 Magento REST API

python - 关于 Pandas 数据框

python - 使用 Numpy 数组从结构返回数据

python - 来自重复键的数组字典?

java - mongo中使用spring data的map类型字段的引用值(dbref)

python - os.system(cmd) 和 subprocess.call(cmd, shell=True) 的执行与 CMD.EXE 不同

python - 将多个数组值匹配到 csv 文件中的行很慢

c# - 从 IEnumerable<KeyValuePair<>> 重新创建字典

xslt - 匹配从 XSLT 中的类型继承的节点