Answers for "namedtuple"

0

namedtuple

# ref: https://realpython.com/python-namedtuple/

>>> from collections import namedtuple
"""
The usage:
ClassAlias = namedtuple(ClassName, ["field1","field2",...], rename=true/false, defaults=["value_n",...])
it returns a namedtuple class "ClassName" with the alias "ClassAlias"  
e.g.
    Person = namedtuple("Person", "name age height")   
	jane = Person("Jane", 25, 1.75)
it has three methods:
	._make(): Person._make(["Jane", 25, 1.75]) generates Person(name='Jane', age=25, height=1.75)
	._asdict(): dict = jane._asdict()
	._replace(): jane = jane._replace(age=26), which  generates a NEW jane
it has two attributes:
	._fields
    ._field_defaults
    
"""
>>> Person = namedtuple("Person", "name children")
>>> john = Person("John Doe", ["Timmy", "Jimmy"])
>>> john
Person(name='John Doe', children=['Timmy', 'Jimmy'])
>>> id(john.children)
139695902374144

>>> john.children.append("Tina")
>>> john
Person(name='John Doe', children=['Timmy', 'Jimmy', 'Tina'])
>>> id(john.children)
139695902374144

>>> hash(john)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Posted by: Guest on July-06-2021

Python Answers by Framework

Browse Popular Code Answers by Language