如何使用当前时间作为属性初始化 class 的实例

How to initialise a instance of a class with current time as attribute

我正在定义一个 class,它有一个时间属性,但默认设置为当前 UTC 时间。

import datetime

class Timer:
    def __init__(self, time = datetime.datetime.utcnow()):
        self.time = time
        print('Instance created at', self.time)
        
        
a = Timer()

问题是一旦定义(或者导入时,如果它在模块中),这个属性就永远设置了! class 的所有新实例都“继承”了 class 的时间,在定义时对其进行了评估,而不是在调用 __init__ 时生成自己的“当前时间”。为什么每次创建新实例时,获取当前 UTC 时间的函数都不计算?

通过为 time 定义默认的 kwarg,当 class 定义对象是 added/interpreted 时,time 被评估,见函数 __defaults__,一个不可变的元组.

>>> class Timer:
...     def __init__(self, time = datetime.datetime.utcnow()):
...         self.time = time
...         print('Instance created at', self.time)
... 
>>> Timer.__init__.__defaults__
# notice how the date is already set here
(datetime.datetime(2021, 2, 19, 15, 22, 42, 639808),)

而您希望在 class 对象实例化时对其求值。

>>> class Timer:
...     def __init__(self, time = None):
...         self.time = time or datetime.datetime.utcnow()
...         print('Instance created at', self.time)
... 
>>> Timer.__init__.__defaults__
(None,)
>>> a = Timer()
Instance created at 2021-02-19 15:04:45.946796
>>> b = Timer()
Instance created at 2021-02-19 15:04:48.313514