How to convert an custom class object to a tuple in Python?(如何将自定义类对象转换为 Python 中的元组?)
问题描述
如果我们在一个类中定义__str__
方法:
If we define __str__
method in a class:
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self, key):
return '{}, {}'.format(self.x, self.y)
我们将能够定义如何将对象转换为 str
类(转换为字符串):
We will be able to define how to convert the object to the str
class (into a string):
a = Point(1, 1)
b = str(a)
print(b)
我知道我们可以定义自定义对象的字符串表示,但是我们如何定义对象的列表——更准确地说,元组——表示?
I know that we can define the string representation of a custom-defined object, but how do we define the list —more precisely, tuple— representation of an object?
推荐答案
tuple
函数"(它实际上是一个类型,但这意味着你可以像函数一样调用它)将接受任何可迭代的,包括一个迭代器,作为它的参数.因此,如果要将对象转换为元组,只需确保它是可迭代的.这意味着实现一个 __iter__
方法,该方法应该是一个生成器函数(其主体包含一个或多个 yield
表达式).例如
The tuple
"function" (it's really a type, but that means you can call it like a function) will take any iterable, including an iterator, as its argument. So if you want to convert your object to a tuple, just make sure it's iterable. This means implementing an __iter__
method, which should be a generator function (one whose body contains one or more yield
expressions). e.g.
>>> class SquaresTo:
... def __init__(self, n):
... self.n = n
... def __iter__(self):
... for i in range(self.n):
... yield i * i
...
>>> s = SquaresTo(5)
>>> tuple(s)
(0, 1, 4, 9, 16)
>>> list(s)
[0, 1, 4, 9, 16]
>>> sum(s)
30
您可以从示例中看到,几个 Python 函数/类型将采用可迭代对象作为其参数,并使用它生成的值序列来生成结果.
You can see from the example that several Python functions/types will take an iterable as their argument and use the sequence of values that it generates in producing a result.
这篇关于如何将自定义类对象转换为 Python 中的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将自定义类对象转换为 Python 中的元组?


基础教程推荐
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01