Skip to content

Instantly share code, notes, and snippets.

@kshirsagarsiddharth
Created July 18, 2020 17:33
Show Gist options
  • Select an option

  • Save kshirsagarsiddharth/8da53e208f2f44af1ebc82112b1a2f76 to your computer and use it in GitHub Desktop.

Select an option

Save kshirsagarsiddharth/8da53e208f2f44af1ebc82112b1a2f76 to your computer and use it in GitHub Desktop.
extending a named tuple
from collections import namedtuple
Bevrage = namedtuple('Bevrage',['name','color','type'])
# defining a class in which named tuple acts as a constructor or #__init__() method
class BeverageContainer(Bevrage):
def container_type(self):
if self.type == 'hot':
return "Use a Mug"
else:
return "A mug is not required"
# defining objects of the named tuple
coffee = BeverageContainer('coffee','light brown','hot')
soda = BeverageContainer('mountain dew','light green','cold')
print(coffee.container_type())
# Output: Use a Mug
print(soda.container_type())
# Output: A mug is not required
# for example you need the attributes for for the named tuples class we have a inbuilt private method _fields
print(Bevrage._fields)
# Output: ('name', 'color', 'type')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment