簡體   English   中英

如何以當前時間為屬性初始化 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__時擁有“當前時間”。 為什么每次創建新實例時都不評估 function 來獲取當前 UTC 時間?

通過定義 time 的默認 kwarg,在添加/解釋 class 定義 object time評估time ,請參見 function __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 object 實例化時對其進行評估。

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM