Reputation: 29
I have an imaginary class:
class Foo:
def __init__(self, **values):
self._value_tuple = tuple(values.items())
And I would like to be able to convert it to tuple
using built-in constructor:
>>> foo = Foo(ham=1, eggs=2, spam=3)
>>> tuple(foo)
(('ham', 1), ('eggs', 2), ('spam', 3))
*I know I can to it manually, by implementing a method like astuple()
. I would like to, if possible, achieve it by calling tuple
constructor.
Upvotes: 1
Views: 68
Reputation: 195438
You can achieve desired functionality by defining __iter__()
method in your class:
class Foo:
def __init__(self, **values):
self._value_tuple = tuple(values)
def __iter__(self):
return self._value_tuple.__iter__()
# or return iter(self._value_tuple)
foo = Foo(ham=1, eggs=2, spam=3)
print(tuple(foo))
Output:
('ham', 'eggs', 'spam')
If you want (keys, values)
, you can store your items in dict:
class Foo:
def __init__(self, **values):
self._value_dict = values
def __iter__(self):
return iter(self._value_dict.items())
foo = Foo(ham=1, eggs=2, spam=3)
print(tuple(foo))
Prints:
(('ham', 1), ('eggs', 2), ('spam', 3))
__iter__()
is part of Python Datamodel. When you implement this method in your class, all functions and syntax constructs that expect something iterable will work with your class without change, that includes parameters in tuple()
.
Upvotes: 3