Home > Net >  Why is it possible to call python's datetime.datetime without using ( )?
Why is it possible to call python's datetime.datetime without using ( )?

Time:12-21

I am wondering why this works

import datetime as dt

test1 = dt.datetime
print(test)

''' prints: <class 'datetime.datetime'>'''

So as far as I understand python, to create an instance of a class you need to call it with brackets like this:

test2 = dt.datetime(2021, 12, 31)

(Calling the constructor method forces you to put in year, month and day).

At first I thought calling datetime like in the first example (without the brackets) must be an attribute or something. But I can't find a single standing attribute "datetime" in the class "datetime".

And the funny thing is - it doesn't matter how you call it, because both lines lead to the same result:

test = dt.datetime
test2 = dt.datetime(2021, 12, 31)

print(test.now())
print(test2.now())

But why? What did I miss? Thanks a lot!

CodePudding user response:

A few things to unpack here.

import datetime as dt

This imports the datetime module and aliases it as dt. Next, dt.datetime is the class datetime inside the module dt (alias for datetime module). Finally, now() is defined as a class method so it does not need to be instantiated. Therefore, dt.datetime.now() calls the class method now of class datetime of module dt whereas the following:

date = dt.datetime(2021, 1, 1)
date.now()

Creates an instance of the datetime class and then have it access the class method now.

See the definition the datetime class within the module:

# Excerpt of datetime.py on Python 3.8.10
class datetime(date):
    @classmethod
    def now(cls, tz=None):
        "Construct a datetime from time.time() and optional time zone info."
        t = _time.time()
        return cls.fromtimestamp(t, tz)

Finally, see here what the Python reference has to say on the classmethod decorator:

A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

  • Related