|
In [231]: t = ("xxj", 18)
In [232]: t
Out[232]: ('xxj', 18)
In [233]: t[0]
Out[233]: 'xxj'
In [234]: t[1]
Out[234]: 18
In [235]: from collections import namedtuple # 导入collectons模块的namedtuple类
In [236]: User = namedtuple('_Yonghu', ["name", "age"]) # 类初始化
In [237]: User
Out[237]: __main__._Yonghu
In [240]: me = User("xxj", 18)
In [241]: me
Out[241]: _Yonghu(name='xxj', age=18)
In [242]: me.name
Out[242]: 'xxj'
In [243]: me.name()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-243-658c183ca1b1> in <module>()
----> 1 me.name()
TypeError: 'str' object is not callable
In [244]: me.age
Out[244]: 18
In [245]: me[0]
Out[245]: 'xxj'
In [246]: me[2]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-246-4bc5e7d46893> in <module>()
----> 1 me[2]
IndexError: tuple index out of range
In [247]: me[0] = "xj"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-247-627de02ba5b9> in <module>()
----> 1 me[0] = "xj"
TypeError: '_Yonghu' object does not support item assignment
In [249]: type(namedtuple)
Out[249]: function
In [250]: type(User)
Out[250]: type
In [251]: type(me)
Out[251]: __main__._Yonghu
In [254]: print(namedtuple.__doc__)
Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
|
|