python - 使类可转换为元组和字典

标签 python python-2.7 dictionary tuples iterable

我想定义一个类,以便它的实例可以同时转换为 tupledict。一个例子:

class Point3:
    ...

p = Point(12, 34, 56)

tuple(p)  # gives (12, 34, 56)
dict(p)   # gives { 'x': 12, 'y': 34, 'z': 56 }

我发现,如果我将 __iter__ 定义为产生单个值的迭代器,那么该实例可以转换为 tuple,如果它产生 double 值,那么它可以被转换为 dict:

class Point3:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    # This way makes instance castable to tuple
    def __iter__(self):
        yield self.x
        yield self.y
        yield self.z

    # This way makes instance castable to dict
    def __iter__(self):
        yield 'x', self.x
        yield 'y', self.y
        yield 'z', self.z

在 Python 2.7 中,有什么方法可以使实例可转换为 tupledict 吗?

最佳答案

您可以将 NamedTuple 子类化(其他类型可用,请咨询您的医生。):

from typing import NamedTuple


class Point(NamedTuple):
    x: float
    y: float
    z: float

    def __add__(self, p):
        return Point(self.x+p.x, self.y+p.y, self.z+p.z)


p = Point(1, 2, 3)
q = Point(5, 5, 5)

print(p.x, p.y, p.z)
print(p+q)
print(tuple(p))

.

$ python pointless.py
1 2 3
Point(x=6, y=7, z=8)
(1, 2, 3)

如果您使用的工具任何都考虑到了惯用的 Python,则命名的元组无论如何都应该是可以接受的。我会试试的!

如果你要使用字典,我建议使用显式的 tuple(p.values())(子类化时)或者 p.coordinatesp.xyz 作为属性(包装时),而不是依赖于场景背后的一些魔法。


旧版,无保修。

from collections import namedtuple


_Point = namedtuple('Point', 'x y z')


class Point(_Point):
    __slots__ = ()

    def __add__(self, p):
        return Point(self.x+p.x, self.y+p.y, self.z+p.z)

关于python - 使类可转换为元组和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51484937/

相关文章:

python - Trello API ~ 只是获取列表的内容?

python - 根据列使用函数满足的条件在 Pandas 中创建新列

python - 如何忽略传递给函数的意外关键字参数?

python - 如何将字典 kwargs 输入到 matplotlib 图例例程中?

python - 无法使用 python 解析 XML 文件。想要从 python 文件中删除一行。帮我删除该行

ruby-on-rails - Ruby 中 For 和 Map 的区别

python - 在 Django 中保存 unicode 字符串时出现 MySQL "incorrect string value"错误

python - Cassandra Spark 写入速度慢

python - 使用单应性降低不透明度的图像对齐

Python 日志记录 - 如何继承根记录器级别和处理程序