快速启动
首先,创建一个名为person的istruct对象,其中first_name和last_name是必需的,而middle_name、dob和email是可选的(指定了默认值)。>>> from istruct import istruct
>>> person = istruct("first_name", "last_name", middle_name="", dob="2000-01-01", email=None)
然后,使用first_name、last_name和middle_name创建person的实例。>>> p = person(first_name="Jim", last_name="Raynor", middle_name="Eugene")
>>> p
istruct(first_name='Jim', last_name='Raynor', email=None, dob='2000-01-01', middle_name='Eugene')
您可以像通常那样检索字段值。>>> p.first_name
'Jim'
>>> p.dob
'2000-01-01'
p是不可变的,这意味着在创建后不能对其进行修改。因此,下面这样的set/delete操作将失败,引发一个AttributeError。>>> p.first_name = "James"
Traceback (most recent call last):
File "", line 1, in
AttributeError: can't set attribute
>>> del p.email
Traceback (most recent call last):
File "", line 1, in
AttributeError: can't delete attribute
istruct只接受命名/关键字参数。它严格禁止按设计使用位置参数。>>> p = person("Jim", "Raynor")
Traceback (most recent call last):
File "", line 1, in
File "/Users/microamp/src/microamp/istruct/istruct/__init__.py", line 52, in _istruct
"(%d found)" % (len(positional),))
TypeError: No positional arguments are allowed in istruct (2 found)
istruct将在省略一个或多个必需的字段时引发TypeError。>>> p = person(last_name="Raynor")
Traceback (most recent call last):
File "", line 1, in
File "/Users/microamp/src/microamp/istruct/istruct/__init__.py", line 56, in _istruct
return nt(**merge_dicts(kwargs, attrs))
TypeError: __new__() missing 1 required positional argument: 'first_name'