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

How to convert an custom class object to a tuple in Python?(如何将自定义类对象转换为 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 中的元组?

基础教程推荐