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

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 checking a shared sec

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 /opt/course/1/context_default_no_kubectl.sh , but without the use of k

标 题: 关于Daniel Guo 律师

发信人: q123452017 (水天一色), 信区: I140 标  题: 关于Daniel Guo 律师 关键字: Daniel Guo 发信站: BBS 未名空间站 (Thu Apr 26 02:11:35 2018, 美东) 这些是lz根据亲身经历在 Immigration版上发的帖以及一些关于Daniel Guo 律师的回 帖,希望大家不要被一些马甲帖广告帖所骗,慎重考虑选择律师。 WG 和Guo两家律师对比 1. fully refund的合约上的区别 wegreened家是case不过只要第二次没有file就可以fully refund。郭家是要两次case 没过才给refund,而且只要第二次pl draft好律师就可以不退任何律师费。 2. 回信速度 wegreened家一般24小时内回信。郭律师是在可以快速回复的时候才回复很快,对于需 要时间回复或者是不愿意给出确切答复的时候就回复的比较慢。 比如:lz问过郭律师他们律所在nsc区域最近eb1a的通过率,大家也知道nsc现在杀手如 云,但是郭律师过了两天只回复说让秘书update最近的case然后去网页上查,但是上面 并没有写明tsc还是nsc。 lz还问过郭律师关于准备ps (他要求的文件)的一些问题,模版上有的东西不是很清 楚,但是他一般就是把模版上的东西再copy一遍发过来。 3. 材料区别 (推荐信) 因为我只收到郭律师写的推荐信,所以可以比下两家推荐信 wegreened家推荐信写的比较长,而且每封推荐信会用不同的语气和风格,会包含lz写 的research summary里面的某个方面 郭家四封推荐信都是一个格式,一种语气,连地址,信的称呼都是一样的,怎么看四封 推荐信都是同一个人写出来的。套路基本都是第一段目的,第二段介绍推荐人,第三段 某篇或几篇文章的abstract,最后结论 4. 前期材料准备 wegreened家要按照他们的模版准备一个十几页的research summary。 郭律师在签约之前说的是只需要准备五页左右的summary,但是在lz签完约收到推荐信 ,郭律师又发来一个很长的ps要lz自己填,而且和pl的格式基本差不多。 总结下来,申请自己上心最重要。但是如果选律师,lz更倾向于wegreened,