Classes and Objects, Modules and Importing

animal_tester file

from datetime import datetime

class Animal:
    def __init__(self):
        pass
        
    def timer(self):
        print(datetime.now())
        
class Horse(Animal):
    def __init__(self):
        super().__init__()

    def show(self):
        super().timer()

if __name__=='__main__':
    a=Horse()
    a.show()


file a.py

from animal_tester import Horse

a=Horse()
a.show()

while importing Horse class from animal tester, will datetime also get imported, if not, why isn’t show() function throwing an error, which is using datetime

Please read the pinned thread and format the code properly, so that we can properly read it and understand what it actually looks like. (Anyway, it doesn’t sound like you actually have a question about classes or objects at all; it sounds like you have a question about modules and importing.)

while importing Horse class from animal tester, will datetime also get
imported, if not, why isn’t show() function throwing an error, which is
using datetime

Basicly: an import only brings a name into the namespace where the
import happens, and code from that module runs in that namespace.

When you do an import 2 basic things happen:

  • the module you name is loaded by Python, and a reference kept in sys.modules
  • the names you import are bound into your local namespace

So let’s look at your import:

 from animal_tester import Horse

(I’m not using the datetime import as an example mostly because the
module name and the class name are the same, which bring confusion.)

First: This loads the animal_tester module and keeps a reference to it
once loaded. If you or something else imports the module again, it isn’t
loaded again - instead the existing reference is reused.

Second: the names you import are bound into your local namespace. In the
import above, you’re importing the name Horse. This is essentially an
assignment statement. You’re taking the animal_tester module and
looking up the name Horse in its namespace. And you’re binding that
to the name Horse in your local namespace.

So: you cause animal_tester to be loaded. Python opens your
animal_tester.py file and runs in, in the newly created namespace for
the module. And names you define are defined in that namespace. This
code:

 class Horse(Animal):
     ..........

defines a class and binds it to the name Horse in the animal_tester
namespace. Similarly, the line:

 from datetime import datetime

looks up the name datetime in the datetime module, and binds it to
the name datetime in the animal_tester namespace.

So there are 3 namespaces we’re talking about here:

  • in the datetime module there are several things, including the datetime class
  • in the animal_tester module there are a few things including the Horse class
  • in your main script you’ve imported a reference to Horse