本文介绍了如何在 Python 中将自定义类对象转换为元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们在一个类中定义了 __str__ 方法:

 class Point():def __init__(self, x, y):自我.x = x自我.y = ydef __str__(self, key):返回 '​​{}, {}'.format(self.x, self.y)

我们将能够定义如何将对象转换为 str 类(转换为字符串):

 a = Point(1, 1)b = str(a)打印(b)

我知道我们可以定义自定义对象的字符串表示,但是我们如何定义列表——更准确地说,元组——对象的表示?

解决方案

tuple函数"(它确实是一种类型,但这意味着您可以像函数一样调用它)将接受任何可迭代对象,包括一个迭代器,作为它的参数.因此,如果您想将对象转换为元组,只需确保它是可迭代的.这意味着实现一个 __iter__ 方法,该方法应该是一个生成器函数(其主体包含一个或多个 yield 表达式).例如

>>>类 SquaresTo:... def __init__(self, n):... self.n = n...定义 __iter__(self):...对于我在范围内(self.n):... 产量 i * i...>>>s = SquaresTo(5)>>>元组(0, 1, 4, 9, 16)>>>清单[0, 1, 4, 9, 16]>>>总和30

您可以从示例中看到,几个 Python 函数/类型将一个可迭代对象作为它们的参数,并使用它生成的值序列来生成结果.

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)

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?

解决方案

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

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

10-28 04:10