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

时间:2013-03-05 16:16:43

标签: python object nested nested-attributes setattr

我正在尝试使用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值?或者是否有另一种更新嵌套对象属性的方法?

3 个答案:

答案 0 :(得分:1)

我认为你需要这样做:

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

由于setattr需要一个要设置的属性名称的字符串

答案 1 :(得分:1)

请勿使用setattr。只需为每个"last"词典的machine键分配值。

(实际上你回答了自己的问题!)

答案 2 :(得分:0)

我不明白为什么,但我可以像这样设置last的值:

  print machine
  print machine["last"]
  print res["time"]

  # this works
  machine["last"] = res["time"]

  print machine

如果有人可以解释,会很好: - )