Skip to main content

python学习笔记之module && package

python的module

  1. import 只能导入模块,不能导入模块中的对象(类、函数、变量等)。如一个模块A(A.py)中有个函数getName,另一个模块不能通过import A.getName将getName导入到本模块,只能用import A。如果想只导入特定的类、函数、变量则用from A import getName即可。
  2. import一个module时,会执行该module的所有方法,并且将该module添加到importing module的命名空间中。A module's body executes immediately the first time the module is imported in a given run of a program...An import statement creates a new namespace containing all the attributes of the module. 如:
  3. fibo.py
    # Fibonacci numbers module
    
    def fib(n):    # write Fibonacci series up to n
        a, b = 0, 1
        while b < n:
            print b,
            a, b = b, a+b
    
    def fib2(n): # return Fibonacci series up to n
        result = []
        a, b = 0, 1
        while b < n:
            result.append(b)
            a, b = b, a+b
        return result
    
    print "EOF"
    In [1]: import fibo
    EOF
    
    In [2]: import fibo
    
    In [3]: fibo.
    fibo.__builtins__      fibo.__doc__           fibo.__hash__          fibo.__package__       fibo.__setattr__       fibo.fib               
    fibo.__class__         fibo.__file__          fibo.__init__          fibo.__reduce__        fibo.__sizeof__        fibo.fib2              
    fibo.__delattr__       fibo.__format__        fibo.__name__          fibo.__reduce_ex__     fibo.__str__           fibo.py                
    fibo.__dict__          fibo.__getattribute__  fibo.__new__           fibo.__repr__          fibo.__subclasshook__  fibo.pyc               
    
    In [3]: fibo.__name__
    Out[3]: 'fibo'
    
    In [4]: fibo.fib(100)
    1 1 2 3 5 8 13 21 34 55 89
    
    In [5]: fibo.fib2(100)
    Out[5]: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    In [6]: from fibo import fib
    
    In [7]: fib(100)
    1 1 2 3 5 8 13 21 34 55 89
    
    In [8]: fib2(100)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    
    /home/forrest/study/python/ in ()
    
    NameError: name 'fib2' is not defined
    
    In [9]: from fibo import *
    
    In [10]: fib2(100)
    Out[10]: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    会 将fibo添加在当前module的名字空间,并且执行fibo.py定义的函数(定义函数表示将函数名添加到module的命名空间)这样就可以通过 fibo访问fibo中定义的方法。并且会执行module中的statement。上面只执行一次,说明python只加载了一次。

    下 面这段话道出了python module的本质,其实也是整个python语言的本质——邦定。1. 变量定义:赋值邦定,对一个x = y==>定义一个变量x,他的值是y,并且将这个变量邦定在其命名空间上(如果是全局变量,那么是该变量所在module)。如果是函数内部变量, 运行时才会执行,并且是邦定在函数对象上。2. 函数定义:def functionName: 定义一个函数对象,并将其邦定在所在命名空间中。 3. 类定义:class clsName: 定义一个类,并将该类对象邦定在其命名空间中。

    Attributes of a module object are normally bound by statements in the module body. When a statement in the body binds a variable (a global variable), what gets bound is an attribute of the module object. The normal purpose of a module body is exactly that of creating the module's attributes: def statements create and bind functions, class statements create and bind classes, and assignment statements can bind attributes of any type. 
    You can also bind and unbind module attributes outside the body (i.e., in other modules), generally using attribute reference syntax M.name (where M is any expression whose value is the module, and identifier name is the attribute name). For clarity, however, it's usually best to limit yourself to binding module attributes in the module's own body. 


python的package
包通常总是一个目录,目录下为首的一个文件便是 _init.py。然后是一些模块文件和子目录,假如子目录中也有 __init_.py 那么它就是这个包的子包了。差不多就像这样吧:
Package1/ __init__.py
    Module1.py
    Module2.py
    Package2/ __init__.py
       Module1.py
       Module2.py
我们可以就这样导入一个包:
import Package1
或者调入一个子模块和子包:
from Package1 import Module1
from Package1 import Package2
import Packag1.Module1
import Packag1.Package2
可以深入好几层包结构:
from Package1.Package2 import Module1
import Package1.Package2.Module1
_init_.py文件
The _init.py files are required to make Python treat the directories as containing packages. In the simplest case, __init.py can just be an empty file, but it can also execute initialization code for the package or set the __all_ variable, described later.
_init.py 控制着包的导入行为。假如 __init_.py 为空,那么仅仅导入包是什么都做不了的。
>>> import Package1
>>> Package1.Module1

Traceback (most recent call last):
 File "", line 1, in ? 
 Package1.Module1

AttributeError: 'module' object has no attribute 'Module1'
我们需要在 _init_.py 里把 Module1 预先导入:
import Module1
测试:
>>> import Package1
>>> Package1.Module1
_init.py 中还有一个重要的变量,叫做 __all_。我们有时会使出一招"全部导入",也就是这样:
from PackageName import *
这时 import 就会把注册在包 _init.py 文件中 __all_ 列表中的子模块和子包导入到当前作用域中来。比如:
__all__ = ['Module1', 'Module2', 'Package2']
测试:
>>> from Package1 import *
>>> Module2
_init_.py其实就是一个普通的python文件,它会在package被导入时执行。
print ">>>in package1.__init__.py"

def say_hello():
    print "Hi, my name is Forrest!"
测试:
In [1]: import package1
>>>in package1.__init__.py

In [2]: package1.say_hello()
Hi, my name is Forrest!
多级package——_init_.py依次被执行
In [1]: import package1.package2
<<>>
<<>>

In [2]: package1.say_hello()
Hi, my name is Forrest!

In [3]: package2.foo_bar()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/home/forrest/study/python/ in ()

NameError: name 'package2' is not defined

In [4]: package1.package2.foo_bar()
foobar!
注意到多级package的import,虽然该路径上的所有packages都被引入了,但是使用的时候仍然必须使用完整路径。
将package/_init_.py改成如下:
print "<<>>"

import package2

def say_hello():
    print "Hi, my name is Forrest!"
In [1]: import package1
<<>>
<<>>

In [2]: package1.package2.foo_bar()
foobar!

In [3]: package2.foo_bar()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/home/forrest/study/python/ in ()

NameError: name 'package2' is not defined
可 以看到也是一样的,必须全路经引用。这是因为在哪个module中import的module,是加入到importing module的名字空间,所以只有该imoprting module可以短路引用,其他的间接引用必须通过import module一路引用过去。


补记:关于Python的module
2011-04-03 星期天 阴雨 

python的module特别像C++中的命名空间(namespacce),因此也就特别像java中的package。
例如,如果你定义了一个namespace mynamespace,那么你可以如下处理:

1> using namespace mynamespace;然后你就可以使用使用mynamespace中的每一个成员。类似与python中的from mynamespace import *
2> using mynamespace::aFunc;在这个文件中可以并且只能使用mynamespace中的aFunc这个定义,直接aFunc()就可以了。类似于python中的from mynamespace import aFunc。
3> 你也可以在使用时直接使用mynamespace::aFunc();来调用mynamespace中的任何成员定义。 在C++中你需要
但 是python跟C++有个非常大的不同是,它的import不仅仅是引入命名空间,还引入了python文件(这点类似于C的#import头文件), 就是说它的import语法共用了(呃,你可以说它责职不单一)。事实上,python的import一定是引入一个module,也就是一个 python文件,如果你想要只引入该module的某个部分,那么可以使用from mudule import xxx。而C++中,你要引入一个namespace中的某一个定义,你必须用两个语句:
首先,引入该定义的头文件:
#include "xxx.h"
然后,引入该头文件的某个命名空间:
#using namespace xxx或者using xxx::yyy
所以,其实python的module,更像是java的package,但是又不像java的package一定是目录,python的module一般是python文件。
其实,作这种对比,目的在于说明,任何语言原理都是差不多的,不需要太纠结于语法细节。应该关注更本质的东西——算法与数据结构。这才是王道

Comments

Popular posts from this blog

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into ...

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checkin...