繁体   English   中英

Python:将类属性作为数组访问

[英]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 一起使用; 使用summax消耗地图对象。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM