我想定义一个类,以便它的实例可以同时转换为 tuple
和 dict
。一个例子:
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 中,有什么方法可以使实例可转换为 tuple
和 dict
吗?
最佳答案
您可以将 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.coordinates
或 p.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/