python - 如何使用当前时间作为属性来初始化类的实例

标签 python class datetime initialization

我正在定义一个具有时间属性的类,该属性默认设置为当前 UTC 时间。

import datetime

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

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

最佳答案

通过为time定义默认kwarg,在添加/解释类定义对象时评估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 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

关于python - 如何使用当前时间作为属性来初始化类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66279891/

相关文章:

c++ - 将名称保存为当前时间日期的文件

python - 将python源代码拆分为多个文件?

c++ - 从其他类获取数组

rest - 解析 Web API 路由中的自定义格式 DateTime 值

c++ - 如何在 C++ 中处理一副纸牌

Java - 处理游戏中可切换效果的最佳方法

mysql - 将空值和格式不正确的日期时间值导入日期时间列 MySQL

python - Pycharm 警告 : must implement all abstract methods

python - 如何测量矢量的移动角度

python - 如何逐行读取 azure 的 Blob ?