Lowercase a field in namedtuple in python -


i have namedtuple redefined __str__()

class mytuple(namedtuple('mytuple', 'field1 field2')):     __slots__ = ()                                                                                                         def __str__(self):         return '{}:{}'.format(self.field1, self.field2) 

every time create instance lowercase value of first field get:

>>>s = mytuple('foo','bar') >>>print s foo:bar 

instead of

foo:bar 

modifying in __str__() not solution in case.

you can override __new__ static method , apply lowercasing there:

class mytuple(namedtuple('mytuple', 'field1 field2')):     __slots__ = ()                                                                                                          def __new__(cls, field1, field2):         """create new instance of mytuple(field1, field2)"""         return super(mytuple, cls).__new__(cls, field1.lower(), field2)      def __str__(self):         return '{}:{}'.format(self.field1, self.field2) 

demo:

>>> collections import namedtuple >>> class mytuple(namedtuple('mytuple', 'field1 field2')): ...     __slots__ = ()                                                                                                     ...     def __new__(cls, field1, field2): ...         """create new instance of mytuple(field1, field2)""" ...         return super(mytuple, cls).__new__(cls, field1.lower(), field2) ...     def __str__(self): ...         return '{}:{}'.format(self.field1, self.field2) ...  >>> mt = mytuple('foo', 'bar') >>> mt mytuple(field1='foo', field2='bar') >>> print(mt) foo:bar >>> mt.field1 'foo' >>> mt.field2 'bar' 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -