【问题标题】:Python Generate some instances using predefined classPython 使用预定义的类生成一些实例
【发布时间】:2019-08-12 02:04:32
【问题描述】:

使用类NickNames,需要使用该类生成一些实例,其中id应该是-增量,nicks-应该从列表中随机选择,timestamp应该采用当前时间戳并存储输出到列表中

目前我得到这种类型的输出[<__main__.NickNames object at 0x00000213547E9AC8>, <__main__.NickNames object at 0x00000213548409E8>] 而不是想要的 1, crown, 119121392391293 (timestamp) 2, makes, 119121392391298 (timestamp) 请帮忙。

这里s the code im 使用

import random
import calendar
import time

nicknames = ['child', 'makes', 'override', 'even', 'eleven', 'householder', 'snowball', 'cure', 'crown']

class NickNames:
  def __init__(self, id, nicks, timestamp):
    self.id = id
    self.nicks = nicks
    self.timestamp = timestamp

res = []

for i in range(2):
    res.append(NickNames(uuid.uuid1(), random.choice(nicknames), calendar.timegm(time.gmtime())))

print(res)

【问题讨论】:

    标签: python class instance generate


    【解决方案1】:

    在 res.append 中将 uuid.uuid1() 替换为 (i + 1)。 将 print(res) 替换为:

    对于 res 中的 obj: print(obj.id, obj.nicks, obj.timestamp)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 2021-05-02
      • 2021-04-19
      • 1970-01-01
      • 2020-09-10
      • 2018-06-12
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多