Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an custom class object to a tuple in Python? [closed]

Tags:

python

tuples

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?

like image 356
acgtyrant Avatar asked Jun 05 '16 07:06

acgtyrant


People also ask

How do you convert an object to a tuple in Python?

Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.

How do you change a set to a tuple?

To convert Python Set to Tuple, use the tuple() method. The tuple() function takes an iterator as a parameter, and in our case, it is a set, and it returns a tuple.

Can tuples be modified after creation?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

How do I turn a list into a tuple?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


1 Answers

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.

like image 189
holdenweb Avatar answered Sep 22 '22 23:09

holdenweb