我正在嘗試撰寫一個類,它在呼叫時,例如:print(TimeNow.time_now)將列印當前時間(但它不是實時的),例如,每次我呼叫它時,它都不會回傳更新的值。
如果我每次都嘗試這個,它會使我的代碼變長,所以我試圖將它編碼在一個類中,以便我可以在任何我想列印時間的地方輕松呼叫它:
time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(time_now)
完整代碼:
import datetime
command = ""
class TimeNow:
time_now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
while command != "quit":
command = input("-> ").lower()
if command == "1":
print(TimeNow.time_now)
uj5u.com熱心網友回復:
這不是類定義的好例子。一個簡單的功能將起作用:
def time_now():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(time_now())
uj5u.com熱心網友回復:
此方法應該適用于您想要的,但需要創建 TimeNow 的實體
import datetime
command = ""
class TimeNow:
@property
def time_now(self):
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
instance = TimeNow()
while command != "quit":
command = input("-> ").lower()
if command == "1":
print(instance.time_now)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418940.html
標籤:
上一篇:過濾熊貓日期的更好方法
