[英]Python: access class properties as array
最初,我想創建一個具有一些string和float屬性的類,其中一個是float格式的時間戳。 擁有該類的約10,000個實例的列表,我想使用這些10,000個時間戳,就好像我有一個用於向量數學運算的numpy數組一樣:
import random
import time
class myclass:
def __init__(self):
# some properties
self.ID=random.random()
self.text1 = 'sometext'
self.text2 = 'some other text'
self.timestamp=time.time()
if __name__ == "__main__":
for i in range(10):
mylist.append(myclass())
# now apply math functions to the timestamps, for example
# max([all timestamps]) or sum([all timestamps])
我可以在數組中排一行而不是一個類實例,但是使用類的許多優點(這里未顯示)丟失了。
你能幫助我嗎?
使用operator.attrgetter
創建時間戳的可調用對象; 與實例列表上的map
一起使用; 使用sum
或max
消耗地圖對象。
from operator import attrgetter
tstamp = attrgetter('timestamp')
print(sum(map(tstamp, mylist)))
print(max(map(tstamp, mylist)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.