gpt4 book ai didi

python - 如何在Python中的嵌套对象中设置属性?

转载 作者:行者123 更新时间:2023-12-01 05:48:37 24 4
gpt4 key购买 nike

我正在首次尝试 Python。

我需要循环日志,解析日志条目,然后更新一个对象,其中包括日志中列出的计算机的嵌套对象。

这就是我所拥有的:

import re
format_pat= re.compile(
r"(?P<host>(?:[\d\.]|[\da-fA-F:])+)\s"
r"(?P<identity>\S*)\s"
r"(?P<user>\S*)\s"
r"\[(?P<time>.*?)\]\s"
r'"(?P<request>.*?)"\s'
r"(?P<status>\d+)\s"
r"(?P<bytes>\S*)\s"
r'"(?P<referer>.*?)"\s'
r'"(?P<user_agent>.*?)"\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()时遇到的错误是

AttributeError: 'dict' object has no attribute ''

但我担心事情没有这么容易......

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

最佳答案

我认为你需要这样做:

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

setattr需要要设置的属性名称的字符串

关于python - 如何在Python中的嵌套对象中设置属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com