这是代码
from datetime import datetime
print(datetime.now())
虽然我们知道第二个datetime是类,但为什么我们没有从datetime类(如d = daytime()
(中首先生成对象呢?
然后调用该类中存在的now()
方法?
像这个d.now()
还是datetime().now()
?
now()
方法是datetime
类的一个类方法。类方法提供了实例化类并返回对象的替代方法。
在datetime.now()
的情况下,class方法实例化具有当前时间戳的datetime
对象并返回它。即使在实例化了datetime
对象之后,now
方法仍然引用该类。
from time import sleep
from datetime import datetime
# d is a datetime object with the current timestamp
d = datetime.now()
sleep(3)
# d2 is *different* datetime object with the current timestamp, 3 seconds later
d2 = d.now()
datetime.now()
是一个类方法。这意味着它对类本身进行操作,而不是对其实例进行操作。如果它是一个实例方法,那就没有意义了——它创建了一个完全新的对象,只依赖于1个因子,即当前时间。