1、导入关键词
【Python】使用 import 语句导入整个模块,使用的时候,必须带上模块名(命名空间)
或使用 from ... import 语句,使用的时候,直接使用模块内的函数,因为是导入到当前命名空间。
例子:
support.py#!/usr/bin/python
#codding=utf-8
def show1(msg):
print('show1:', msg)
return 'ok'
def show2(msg):
print('show2:', msg)
return 'ok'
test.py#!/usr/bin/python
#coding=utf-8
import support
support.show1('hello')
support.show2('hello')
运行后:E:\python370\python.exe D:/web/python/test/test.py
show1: hello
show2: hello
test2.py , 使用 from ... import xx 后,可直接使用模块内的函数名,因为是导入到本文件的命名空间了。test2.py 只导入了 support.show1() 方法,show2() 不能使用。#!/usr/bin/python
#coding=utf-8
from support import show1
show1('hello')
运行后:E:\python370\python.exe D:/web/python/test/test2.py
show1: hello
test3.py , 使用了 from ... import * 方式导入模块后,就把其他模块下所有的方法都导入到本文件的命名空间下,可直接使用函数名#!/usr/bin/python
#coding=utf-8
from support import *
show1('hello')
show2('world')
【PHP】分两部分导入,第一部分是导入文件,使用 include require 等关键字。
第二部分是引用命名空间,使用 use xxxx;
调用命名空间下的方法,必须带命名空间,也就说不能把命名空间的函数导入到本文件的命名空间里面。
例子:
func.php<?php
namespace func;
function show1($msg){
echo 'show1:', $msg, "\n";
}
function show2($msg){
echo 'show2:', $msg;
}
test.php<?php
namespace test;
include_once "func.php";
use func;
func\show1('hello');
func\show2('hello');
运行后D:\web\test>php test.php
show1:hello
show2:hello
2、包导入
【Python】
包是一个分层次的文件目录结构,它定义了一个由模块及子包,和子包下的子包等组成的 Python 的应用环境。
简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。__init__.py 用于标识当前文件夹是一个包。test.py
goods
|-- __init__.py
|-- jd.py
|-- taobao.py
goods/jd.py#!/usr/bin/python
#coding=utf-8
def detail(name):
print( '''jingdong's goods is '''+name)
def price(price):
print( '''jingdong's price is ''', price)
goods/taobao.py#!/usr/bin/python
#coding=utf-8
def detail(name):
print( '''taobao's goods is '''+name)
def price(price):
print( '''taobao's price is '''+price)
goods/__init__.py#!/usr/bin/python
#coding=utf-8
print('__init__:',__name__)
test.py#!/usr/bin/python
#coding=utf-8
import goods.jd, goods.taobao
goods.jd.detail('帽子')
goods.jd.price(123)
goods.taobao.detail('帽子')
goods.taobao.price('123')
运行:goods/__init__.pyE:\python370\python.exe D:/web/python/test/goods/__init__.py
__init__: __main__
运行:test.pyE:\python370\python.exe D:/web/python/test/test.py
__init__: goods
jingdong's goods is 帽子
jingdong's price is 123
taobao's goods is 帽子
taobao's price is 123