Python Modules

Wat is een module?

Denk aan modules die vergelijkbaar zijn met een codebibliotheek.

Een module is een bestand dat een reeks functies bevat en in de applicatie wordt gerefereerd.

Maak een module

Om een module te maken, slaat u de benodigde code op in een bestand met de bestandsextensie .py Opslaan van code in het bestand:

Example

In het bestand genaamd mymodule.py Opslaan van code in het bestand:

def greeting(name):
  print("Hello, " + name)

gebruik de module

Nu kunnen we import stuk code aan om de net gemaakte module te gebruiken:

Example

Importeer de module genaamd mymodule van de module en roep de volgende greeting Functions:

import mymodule
mymodule.greeting("Bill")

Run Example

Note:Gebruik de volgende syntaxis als u functies uit de module gebruikt:

module_name.function_name

Variabelen in de module

Een module kan de al beschreven functies bevatten, maar kan ook verschillende soorten variabelen (arrays, dictionaries, objecten, enz.) bevatten:

Example

In het bestand mymodule.py Opslaan van code in het bestand:

person1 = {
  "name": "Bill",
  "age": 63,
  "country": "USA"
}

Example

Importeer de module genaamd mymodule Importeer de module en raadpleeg de person1-dictionary:

import mymodule
a = mymodule.person1["age"]
print(a)

Run Example

Naam van de module

U kunt de naam van de modulebestand naar willekeurig kiezen, maar de bestandsextensie moet zijn .py.

Hernoem de module

U kunt het gebruiken bij het importeren van modules. as Sleutelwoord om een alias te maken:

Example

Maak een alias voor mymodule: mx:

import mymodule as mx
a = mx.person1["age"]
print(a)

Run Example

Ingebouwde modules

Er zijn enkele ingebouwde modules in Python die u op elk moment kunt importeren.

Example

Import and use platform Module:

import platform
x = platform.system()
print(x)

Run Example

Use the dir() function

There is a built-in function that can list all function names (or variable names) in a module.dir() Functions:

Example

List all defined names belonging to the platform module:

import platform
x = dir(platform)
print(x)

Run Example

Note:The dir() function can be used for all modules and also for modules you create yourself.

Import from module

You can use the from keyword to import only parts from the module.

Example

The module named mymodule has a function and a dictionary:

def greeting(name):
  print("Hello, " + name)
person1 = {
  "name": "Bill",
  "age": 63,
  "country": "USA"
}

Example

Import only person1 dictionary from module:

from mymodule import person1
print(person1["age"])

Run Example

Tip:When importing using the from keyword, do not use the module name when referencing elements within the module. Example: person1["age"], not mymodule.person1["age"].