python set 嵌套,如何在Python中设置嵌套对象的属性?
发布日期:2022-02-21 12:50:34 浏览次数:38 分类:技术文章

本文共 1476 字,大约阅读时间需要 4 分钟。

我第一次尝试Python。在

我需要遍历一个日志,解析日志条目,然后更新一个对象,其中包括日志中列出的机器的嵌套对象。在

这就是我所拥有的:import re

format_pat= re.compile(

r"(?P(?:[\d\.]|[\da-fA-F:])+)\s"

r"(?P\S*)\s"

r"(?P\S*)\s"

r"\[(?P.*?)\]\s"

r'"(?P.*?)"\s'

r"(?P\d+)\s"

r"(?P\S*)\s"

r'"(?P.*?)"\s'

r'"(?P.*?)"\s*'

)

from json import JSONEncoder

class MyEncoder(JSONEncoder):

def default(self, o):

return o.__dict__

# JSON response object

class ResponseObject(object):

def __init__(self, dict):

self.__dict__ = dict

# check for JSON response object

try:

obj

except NameError:

obj = ResponseObject({})

test = ['2001:470:1f14:169:15f3:824f:8a61:7b59 - SOFTINST [14/Nov/2012:09:32:31 +0100] "POST /setComputer HTTP/1.1" 200 4 "-" "-" 102356']

# log loop

for line in test:

try:

# try to create object from log entry

m = format_pat.match(line)

if m:

res = m.groupdict()

res["status"] = int(res["status"])

# register machine if not done

if not hasattr(obj, res["user"]):

setattr(obj, res["user"], {"downtime":"0","flag":"false","downstart":"0","init":res["time"],"last":"","uptime":"","downtime":"","totaltime":""})

machine = getattr(obj, res["user"])

flag = machine["flag"]

start = machine["downstart"]

down = machine["downtime"]

last = machine["last"]

print "done"

# set last

last = res["time"]

# PROBLEM this does not work

setattr(machine, last, res["time"])

print machine

else:

print "nope"

except:

print "nope base"

print MyEncoder().encode(obj)

尝试setattr()时遇到的错误是

^{pr2}$

但我担心这不是那么容易。。。在

问题:

如何使用“setattr”更新嵌套对象中的last值?或者有其他方法来更新嵌套的对象属性吗?在

转载地址:https://blog.csdn.net/weixin_33958381/article/details/116165796 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:linux远程抓包 mac地址,Mac或Linux中对Android抓包
下一篇:php 栈加密,PHP 数据结构与算法之《栈》_php

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月18日 14时08分54秒