Python:通过字符串中的名称访问结构字段 [英] Python: access structure field through its name in a string
本文介绍了Python:通过字符串中的名称访问结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Scapy中,我想比较任意两个数据包a
和b
之间的头域数量.此字段列表是预定义的,例如:
In Scapy, I want to compare a number of header fields between any two packets a
and b
. This list of fields is predefined, say:
fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header
通常我会单独进行:
if a[IP].tos == b[IP].tos:
... do stuff...
是否有任何方法可以从字符串列表访问这些数据包字段,包括每个字符串的名称?喜欢:
Is there any way to access those packet fields from a list of strings including what each one of them is called? Like:
for field in fieldsToCompare:
if a[IP].field == b[IP].field:
... do stuff...
推荐答案
您可以使用 getattr()
.这些行是等效的:
You can use getattr()
. These lines are equivalent:
getattr(x, 'foobar')
x.foobar
setattr()
是其对应内容.
setattr()
is its counterpart.
这篇关于Python:通过字符串中的名称访问结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文