Python:通过名称在字符串中访问结构字段(Python: access structure field through its name in a string)

编程入门 行业动态 更新时间:2024-10-27 08:24:34
Python:通过名称在字符串中访问结构字段(Python: access structure field through its name in a string)

在Scapy中,我想比较任意两个数据包a和b之间的多个头字段。 这个字段列表是预定义的,例如:

fieldsToCompare = ['tos', 'id', 'len', 'proto'] #IP header

通常我会单独做:

if a[IP].tos == b[IP].tos: ... do stuff...

有没有办法从字符串列表中访问这些数据包字段,包括每个字符串被称为什么? 喜欢:

for field in fieldsToCompare: if a[IP].field == b[IP].field: ... do stuff...

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

Normally I would do it individually:

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() 。 这些线是相同的:

getattr(x, 'foobar') x.foobar

setattr()是它的对手。

You can use getattr(). These lines are equivalent:

getattr(x, 'foobar') x.foobar

setattr() is its counterpart.

更多推荐

本文发布于:2023-07-28 16:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1306853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   字符串   名称   结构   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!