When importing from a python module is it a class that gets imported or a function?

78 views Asked by At

In Code Academy's python training there's a lesson about importing datetime. The syntax is:

from datetime import datetime

After importation I'm able to write now = datetime.now() and evaluate now.hour, now.minute and now.second. I see in the datetime module that .now (), .hour, .minute and .second are defined in the datetime class. Which leads me to interpret the import statement as saying:

from datetime module import datetime class

And so it seems that access to the datetime class is what gave me access to the .now(), .hour, .minute and .second definitions.

But later I discovered that I'm also able to evaluate now.month, now.day and now.year. Even though .month .day and .year are not in the datetime class. Rather they're in a different class called date.

How could I access definitions from the date class when it seems I only imported the datetime class?

1

There are 1 answers

1
MattDMo On BEST ANSWER

If you look through the source of datetime.py, you'll notice this line (line 1290 in 3.4.2):

class datetime(date):

This is the class definition for the datetime class, which is inheriting from the previously-defined date class. Therefore, a datetime object (an instantiation of the datetime class) can access properties and methods defined in the date class, as long as they were not overridden by datetime.

You can read more about classes here, and about inheritance in particular here.