0

I'm new to python so please just don't blast me.

import matplotlib.pyplot as plt
plt.xlabel('sepal length [cm]')

I know that the import works with modules and I also know what I module is. The fact is that when a call the xlabel method same information is stored in plt as it would act as an object. In fact, if I then call

plt.show()

It appears a graph with "sepal length [cm]" in the x-axis.

So when I import a module it acts like an object? Is there a more precise definition of this?

A.D.
  • 2,352
  • 2
  • 15
  • 25
Lokty
  • 95
  • 5

2 Answers2

1

Everything in Python is an object (1 is an object, not a special primitive type like in Java, classes are objects, functions are objects, etc.). Modules are just objects of the module type (which you never instantiate directly, it's just created implicitly when a module is imported), and their attributes are the globally defined names within the module.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

As you noted, modules can feel like objects, since the functions can modify state in the module. There are important differences, however. For one, you can't make new instances. Importing a module again will just act like another name for the existing module. For instance, this will show the plot:

import matplotlib.pyplot as plt1
import matplotlib.pyplot as plt2
plt1.plot([1, 2, 1])
plt2.show()

So there is always only one state per module, as far as I understand.

See also this question.

nnnmmm
  • 7,964
  • 4
  • 22
  • 41
  • 1
    Actually, the caching behavior for modules can be explicitly overridden to import a module more than once. It's a terrible idea, but it can be done, you just delete the entry for the module in `sys.modules` then `import` it again, and you get a separate copy. – ShadowRanger Dec 30 '17 at 11:23
  • @ShadowRanger the "how to 'impress' your colleagues" methodology :) – Jon Clements Dec 30 '17 at 11:29
  • 1
    Well you can instantiate a module object, sort of, but whether you *should* is another matter. `import sys` (or any other module) then `y = type(sys)('y')` where `y` is the new module object, but I have no idea why you would want to do that. – cdarke Dec 30 '17 at 11:54