[Tutor] Details regarding namedtuple
Mats Wichmann
mats at wichmann.us
Sat Sep 14 13:51:50 EDT 2019
On 9/14/19 11:25 AM, Gursimran Maken wrote:
> Hi All,
>
> I would like to understand the use of first argument i.e. typename in
> namedtuple collection.
> collections.namedtuple (typename, field_names)
>
> Example 1:
> from collections import namedtuple
> person = namedtuple ('person', 'age gender')
> Sam = person(age=12, gender='M')
> Sam.age
>
> Example 2:
> from collections import namedtuple
> person = namedtuple ('xyz', 'age gender')
> Sam = person(age=12, gender='M')
> Sam.age
> Pam = xyz(age=22, gender='F')
> Pam.age
>
> In example 1, both typename and variable name are same i.e. "person", and
> we we print Sam.age we get output as 12.
>
> In example 2, both typename and variable name are different i.e. "person"
> and "xyz" respectively, and we we print Sam.age we get output as 12 but
> when we type below statement we get an error, why?
> Pam = xyz(age=22, gender='F')
it's used to set the name of the generated class.
>>> Sam = person(age=12, gender='M')
>>> Sam
xyz(age=12, gender='M')
>>> person.__name__
'xyz'
>>>
More information about the Tutor
mailing list