Is this a pure way to implement some kind of __tuple__ method?

Let an object a of class A have the attribute .my_tuple. I want to be able to get this attribute call.

tuple(a)

A simpler way that I found is to define A, for example:

class A():
    # other things
    def __iter__(self):
        return self.my_tuple.__iter__()

But it seems a little dirty: I understand that "tuple (a)" will iterate over self.my_tuple to build a copy of it, while I only want a pointer to it ... Is built-in - the "tuple" is optimized to solve these affairs? If not, this is the best way to do this (keep it "pythonic": in my case it makes sense to drop the A-type into a tuple).

+4
source share
2 answers

tuple() . , .

, , iter() __iter__ . , , , :

  • , , tuple().
  • , , tuple , , , tuple-iterator __iter__. , , .

tuple() ( iter() len() ), tuple() self.my_tuple. , , .

:

, , a.b, a.c, a.d, (), (b, c, d)

, collections.namedtuple:

class A(collections.namedtuple('A', 'b c d')):
    # whatever methods you need

, , A , , , .

+4

, , :

>>> class Tupleable(object):
    def __iter__(self):
        return (v for v in self.__dict__.itervalues())

>>> class A(Tupleable):
    def __init__(self, a, b):
        self.a = a
        self.b = b

>>> a = A(2, 'e')
>>> tuple(a)
(2, 'e')

, , , , .

+2

Source: https://habr.com/ru/post/1534219/


All Articles