【Python】Basics - Modules

Posted by 西维蜀黍 on 2019-09-18, Last Modified on 2024-05-02

Function

Importing an Entire Module

To start importing functions, we first need to create a module. A module is a file ending in .py that contains the code you want to import into your program. Let’s make a module that contains the function make_pizza(). To make this module, we’ll remove everything from the file pizza.py except the function make_pizza():

# pizza.py
def make_pizza(size, *toppings):
		"""Summarize the pizza we are about to make.""" 
		print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") 
		for topping in toppings:
			print("- " + topping)

Now we’ll make a separate file called making_pizzas.py in the same directory as pizza.py. This file imports the module we just created and then makes two calls to make_pizza():

# making_ pizzas.py
import pizza

# make_pizza(16, 'pepperoni') 																	error
# make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')  error

pizza.make_pizza(16, 'pepperoni') 
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

When Python reads this file, the line import pizza tells Python to open the file pizza.py and copy all the functions from it into this program. You don’t actually see code being copied between files because Python copies the code behind the scenes as the program runs. All you need to know is that any function defined in pizza.py will now be available in making_pizzas.py.

Importing Specific Functions

You can also import a specific function from a module. Here’s the general syntax for this approach:

from module_name import function_name

You can import as many functions as you want from a module by separating each function’s name with a comma:

from module_name import function_0, function_1, function_2

The making_pizzas.py example would look like this if we want to import just the function we’re going to use:

from pizza import make_pizza

make_pizza(16, 'pepperoni') 
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

With this syntax, you don’t need to use the dot notation when you call a function. Because we’ve explicitly imported the function make_pizza() in the import statement, we can call it by name when we use the function.

Using as to Give a Function an Alias

If the name of a function you’re importing might conflict with an existing name in your program or if the function name is long, you can use a short, unique alias—an alternate name similar to a nickname for the func-tion. You’ll give the function this special nickname when you import the function.

Here we give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The as keyword renames a function using the alias you provide:

from pizza import make_pizza as mp

mp(16, 'pepperoni') 
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

The import statement shown here renames the function make_pizza() to mp() in this program. Any time we want to call make_pizza() we can simply write mp() instead, and Python will run the code in make_pizza() while avoiding any confusion with another make_pizza() function you might have written in this program file.

The general syntax for providing an alias is:

from module_name import function_name as fn

Using as to Give a Module an Alias

You can also provide an alias for a module name. Giving a module a short alias, like p for pizza, allows you to call the module’s functions more quickly. Calling p.make_pizza() is more concise than calling pizza.make_pizza():

import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

The module pizza is given the alias p in the import statement, but all of the module’s functions retain their original names. Calling the functions by writing p.make_pizza() is not only more concise than writing pizza.make_pizza(), but also redirects your attention from the module name and allows you to focus on the descriptive names of its functions. These function names, which clearly tell you what each function does, are more important to the readability of your code than using the full module name.

The general syntax for this approach is:

import module_name as mn

Imported Functions Overlay

module1.py

def foo():
    print('hello, world!')

module2.py

def foo():
    print('goodbye, world!')

If we run test.py like below, the foo() called will be the one that is imported in the end, as this one will overlap the prior one improted before.

test.py

from module1 import foo
from module2 import foo

foo()	# print goodbye, world!

test.py

from module2 import foo
from module1 import foo

foo()	# print hello, world!

Classes

Importing Multiple Classes from a Module

You can import as many classes as you need into a program file. If we want to make a regular car and an electric car in the same file, we need to import both classes, Car and ElectricCar:

# Car.py
class Car():
		"""A simple attempt to represent a car."""
		
		def init(self, make, model, year):
				"""Initialize attributes to describe a car.""" 
				self.make = make 
        self.model = model 						
				self.year = year

		def get_descriptive_name(self):
				"""Return a neatly formatted descriptive name.""" 
				long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
				return long_name.title()

class ElectricCar(Car):
		"""Represent aspects of a car, specific to electric vehicles."""
		def __init__(self, make, model, year):
      	"""Initialize attributes of the parent class.""" 
        super().__init__(make, model, year)
# my_cars.py
from car import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2016) 
print(my_beetle.get_descriptive_name())

my_tesla = ElectricCar('tesla', 'roadster', 2016) 
print(my_tesla.get_descriptive_name())

Importing an Entire Module

You can also import an entire module and then access the classes you need using dot notation. This approach is simple and results in code that is easy to read. Because every call that creates an instance of a class includes the module name, you won’t have naming conflicts with any names used in the current file.

Here’s what it looks like to import the entire car module and then create a regular car and an electric car:

# my_cars.py
import car
my_beetle = car.Car('volkswagen', 'beetle', 2016) 
print(my_beetle.get_descriptive_name())

my_tesla = car.ElectricCar('tesla', 'roadster', 2016) 
print(my_tesla.get_descriptive_name())

We import the entire car module. We then access the classes we need through the module_name.class_name syntax. We again create a Volkswagen Beetle, and we create a Tesla Roadster.

Reference

  • Learning Python
  • Python Crash Course (2nd Edition) : A Hands-On, Project-Based Introduction to Programming