Created
July 18, 2020 17:33
-
-
Save kshirsagarsiddharth/8da53e208f2f44af1ebc82112b1a2f76 to your computer and use it in GitHub Desktop.
extending a named tuple
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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