gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:35:57 26 4
gpt4 key购买 nike

我想定义一个类,以便它的实例可以同时转换为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com