如何将自定义类对象转换为 Python 中的元组?

2023-08-31Python开发问题
17

本文介绍了如何将自定义类对象转换为 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 中的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10