简体   繁体   English

Python:循环并分配嵌套对象属性的简单方法?

[英]Python: easy way to loop through and assign nested object attributes?

I have a list of object attributes that I wish to re-assign. 我有一个我想重新分配的对象属性列表。 Some of the attributes are within nested objects. 某些属性位于嵌套对象中。 Is there a simple way to assign all of these attributes using a single loop or otherwise. 有没有一种简单的方法可以使用单个循环或其他方式分配所有这些属性。

Here is my example code: 这是我的示例代码:

from datetime import datetime
import time

class Foo:
  pass

class Bar:
  pass

now = time.time()

foo = Foo()
foo.time1 = now
foo.time2 = now + 1000
foo.other = 'not just times'

foo.bar = Bar()
foo.bar.btime1 = now - 1000
foo.bar.btime2 = now - 2000
foo.bar.bother = 'other stuff'

## seemingly easy way
# just sets time to reference the result, doesn't alter foo
for time in foo.time1, foo.time2, foo.bar.btime1, foo.bar.btime2:
  time = datetime.fromtimestamp( time ).strftime('%c')

## 'dirty' way
for time in 'time1', 'time2':
  val = getattr(foo, time)
  val = datetime.fromtimestamp( val ).strftime('%c')
  setattr( foo, time, val )

# have to do another loop for each nested object
for time in 'btime1', 'btime2':
  val = getattr(foo.bar, time)
  val = datetime.fromtimestamp( val ).strftime('%c')
  setattr( foo.bar, time, val )

# goal is to format everything nicely...
print (
    'Time1:  {0.time1}\n'
    'Time2:  {0.time2}\n'
    'Other:  {0.other}\n'
    'BTime1: {0.bar.btime1}\n'
    'BTime1: {0.bar.btime2}\n'
    'BOther: {0.bar.bother}'
    ).format(foo)

Being the python noob that I am, I tried looping through the attributes first and obviously that didn't work for well documented reasons. 作为我的python noob,我尝试首先循环遍历这些属性,显然这些原因并没有得到很好的记录。 The only alternative I can see is using setattr , however this doesn't work well with the nested objects as shown. 我能看到的唯一替代方法是使用setattr ,但这对嵌套对象不起作用,如图所示。 Although it 'feels like' there should be an easier way to do the assignments since this is a simple thing to achieve with pointers in other languages. 虽然它'感觉'应该有一种更简单的方法来进行分配,因为这是用其他语言指针实现的简单方法。

To be clear this question is about the nested object assignments. 要明确这个问题是关于嵌套对象分配。 But since I am obviously attempting to convert an object containing timestamps to a one containing formatted date/time strings and print it, any other suggestions on how to get to the formatted output would be helpful :) 但是因为我显然试图将包含时间戳的对象转换为包含格式化日期/时间字符串的对象并打印它,所以关于如何获取格式化输出的任何其他建议将是有帮助的:)

In general, this sort of thing is really a design problem that is only pretending to be an implementation problem. 一般来说,这种事情实际上是一个设计问题,只是假装是一个实现问题。 To solve it, reorganize so that you do the work up front. 要解决它,请重新组织,以便您事先做好工作。 Of course, presumably the reason you didn't do this the first time around was in order to avoid duplication of the time formatting code. 当然,大概是你第一次没有这样做的原因是为了避免重复时间格式化代码。 But simply by saying that, the solution becomes obvious: wrap it in a function. 但简单地说,解决方案变得显而易见:将其包装在一个函数中。

def formatted_time(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%c')

foo = Foo()
foo.time1 = formatted_time(now)
foo.time2 = formatted_time(now + 1000)
foo.other = 'not just times'

foo.bar = Bar()
foo.bar.btime1 = formatted_time(now - 1000)
foo.bar.btime2 = formatted_time(now - 2000)
foo.bar.bother = 'other stuff'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python方式遍历对象属性并分配新属性 - Pythonic way to to loop through object attributes and assign new attribute 有没有办法在for循环python中分配对象 - Is there a way to assign object in a for loop python Python:在嵌套namedtuple上替换属性的简便方法? - Python: Easy way to replace attribute on nested namedtuple? Python:从评估的字符串列表中循环遍历字典参数的简便方法? - Python: Easy way to loop through dictionary parameters from a list of evaluated strings? 如何在循环中分配 class 属性 Python - How to assign class attributes in a loop Python 创建一种简单的方法来读取保存在复杂的嵌套python字典中的JSON对象 - Creating an easy way to read a JSON object saved in a complex, nested python dictionary 在Python中使用对象的属性进行循环 - For loop with object's attributes in Python 有没有一种简单的方法来检查对象是否在python中是可序列化的? - Is there an easy way to check if an object is JSON serializable in python? 有没有办法遍历一个列表,并分配一个变量 - Is there a way to loop through a list, and assign a variable 有没有一种在Django Model / Python类中创建派生属性的简单方法? - Is there an easy way to create derived attributes in Django Model/Python classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM