簡體   English   中英

Python:循環並分配嵌套對象屬性的簡單方法?

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

我有一個我想重新分配的對象屬性列表。 某些屬性位於嵌套對象中。 有沒有一種簡單的方法可以使用單個循環或其他方式分配所有這些屬性。

這是我的示例代碼:

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)

作為我的python noob,我嘗試首先循環遍歷這些屬性,顯然這些原因並沒有得到很好的記錄。 我能看到的唯一替代方法是使用setattr ,但這對嵌套對象不起作用,如圖所示。 雖然它'感覺'應該有一種更簡單的方法來進行分配,因為這是用其他語言指針實現的簡單方法。

要明確這個問題是關於嵌套對象分配。 但是因為我顯然試圖將包含時間戳的對象轉換為包含格式化日期/時間字符串的對象並打印它,所以關於如何獲取格式化輸出的任何其他建議將是有幫助的:)

一般來說,這種事情實際上是一個設計問題,只是假裝是一個實現問題。 要解決它,請重新組織,以便您事先做好工作。 當然,大概是你第一次沒有這樣做的原因是為了避免重復時間格式化代碼。 但簡單地說,解決方案變得顯而易見:將其包裝在一個函數中。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM