1 引言
Python编程的最强项是处理大量结构化或非结构化的数据,这些数据可以保存成不同的格式,例如txt, Json, list, range, dictionary, tuple等。而要从这些数据对象中取出特定的数据或变量,必须明白对象和变量的类型。特别在处理多个对象时,编程时很容易出错。因此需要首先检查变量的类型。本文简要描述了使用Itasca软件时使用的变量类型检查工具type()和help()。
2 type()
type()用来检查一个变量的类型。在编程语言的初始用法中,不限于Python, type()用来检查一个变量是整形还是实型,在Python中,以我自己过去的经历,主要使用type()检查一个变量是list, dictionary还是tuple, 因为这三种存储类型是Python最常用的数据格式。而在Itasca软件中,type()可以用来检查变量是一个类还是字典或列表,例如:
zone_maxid = it.zone.find(it.zone.maxid())
print(type(zone_maxid))
zone_maxid的类型是<class 'itasca.zone.Zone'>,这是一个类,不是一个字典或列表,因此我们必须使用方法来返回或赋予该单元的值。
print(zone_maxid.density())
print(zone_maxid.geom_test())
print(zone_maxid.id())
print(zone_maxid.vol_deformed())
print(zone_maxid.vol())
print(zone_maxid.type())
print(zone_maxid.props())
type()最重要的一个用途是检查结构元的类型,当进行支护模拟时,有时需要在一个模型中联合使用多种结构元,如Cable, Beam, Liner, Shell等组合,在这种情况下,必须能够正确区分各种类型的单元,这也是支护模拟最容易出错的地方。总的代码格式是:
type(struct_elem) is it.structure.str_type
其中str_type可以是Cable, Beam, Pile, Shell, Geogrid, Liner的任意一个,取决于应用场景。下面的半伪代码显示了这种应用。
for s in it.structure.list()
if type(s) is it.structure.Cable:
print('Cable单元的id')
elif type(s) is it.structure.Beam:
print('Beam单元的id')
Itasca软件需要使用各种各样的list, 尽管在最新版的软件中对list的操作作了大量改进【FISH: Loop语句的进化】,而且增加了list数组,但不如在Pyhton中使用方便。
3 help()
另一个检查Python变量的方法是使用help()命令。由于Itasca软件的类与实例对象很难有明确界限,例如zone.Zone,block.zone.Zone.props,dfn.fracture.Fracture等,因此使用help()函数可以不必查看用户手册而快速得到帮助,来检查使用的函数是否正确以及函数的功能。下面列举几个例子:
(1) help(it.zone.count) -> int. Get the number of zones.
(2) help(it.zone.find) ->Zone object. Get the zone object with the given ID number.
(3) help(it.structure.count) -> int. Get the number of structural elements.
(4) help(it.dfn.fracture.count) -> int. Get the number of fractures.
(5) help(z.pos) -> vec. Get the zone centroid location (vector).
(6) help(z.set_prop) method of itasca.block.zone.Zone instance. (property_name: str, value: any) -> None. Set a surface property of this zone.