`

Python3标准库学习(二)

 
阅读更多

== _ _builtin_ _ 模块 ==



这个模块包含 Python 中使用的内建函数. 一般不用手动导入这个模块; Python会帮你做好一切.

 

=== 使用元组或字典中的参数调用函数 ===

Python允许你实时地创建函数参数列表. 只要把所有的参数放入一个元组中或者字典中

示例代码如下:

 

#-*- encoding:gb2312 -*-

'''
Created on 2012-5-1

@author: Administrator
'''

def transimtParams(a,b):
    print(a,b)
#python2 的写法
#使用元组的参数调用函数
#apply(function, ("whither","canada?"))
#apply(function, (1, 2+3))
#使用字典中的参数调用函数
#apply(function, ("crunchy",), {"b": "frog"})
#apply(function, (), {"a": "crunchy", "b": "frog"})

#python3 的写法
#使用元组的参数调用函数
transimtParams(*("whither","canada?"))
transimtParams(*(1,2+3))
#使用字典中的参数调用函数
transimtParams(*("crunchy",),**{"b":"frog"})
transimtParams(**{"a":"crunchy", "b":"frog"})

  运行结果:

whither canada?
1 5
crunchy frog
crunchy frog

 

元组参数前面加*号,字典参数前面加**号。

 

===调用基类的构造函数===

示例:

 

class Rectangle:
    def __init__(self, color="white", width=10, height=10):
        print("create a", color, self, "sized", width, "x", height)

class RoundedRectangle(Rectangle):
    def __init__(self, **kw):
        #apply(Rectangle.__init__, (self,), kw)
        Rectangle.__init__(*(self,),**kw)

rect = Rectangle(color="green", height=100, width=100)
rect = RoundedRectangle(color="blue", height=20)
 

运行结果:

create a green <__main__.Rectangle object at 0x00BB2E70> sized 100 x 100
create a blue <__main__.RoundedRectangle object at 0x00C6E190> sized 10 x 20

 

 

===加载和重载模块===

 

如果你写过较庞大的 Python 程序, 那么你就应该知道 ``import`` 语句是用来导入外部模块的
(当然也可以使用 ``from-import`` 版本). 不过你可能不知道 ``import`` 其实是靠调用内建
函数 ``_ _import_ _`` 来工作的.

通过这个戏法你可以动态地调用函数. 当你只知道模块名称(字符串)的时候, 这将很方便.
[Example 1-4 #eg-1-4] 展示了这种用法, 动态地导入所有以 "``-plugin``" 结尾的模块.

====Example 1-4. 使用 _ _import_ _ 函数加载模块====[eg-1-4]

 

import glob, os

modules = []

for module_file in glob.glob("*-plugin.py"):
    try:
        module_name, ext = os.path.splitext(os.path.basename(module_file))
        module = __import__(module_name)
        modules.append(module)
    except ImportError:
        pass # ignore broken modules

# say hello to all modules
for module in modules:
    module.hello()
 

注意这个 plug-in 模块文件名中有个 "-" (hyphens). 这意味着你不能使用普通的 ``import`` 命令, 因为 Python 的辨识符不允许有 "-" .

 

[Example 1-5 #eg-1-5] 展示了 [Example 1-4 #eg-1-4] 中使用的 plug-in .

====Example 1-5. Plug-in 例子====[eg-1-5]

 

File: example-plugin.py

def hello():
    print "example-plugin says hello"

 

 [Example 1-6 #eg-1-6] 展示了如何根据给定模块名和函数名获得想要的函数对象.

====Example 1-6. 使用 _ _import_ _ 函数获得特定函数====[eg-1-6]


File: builtin-import-example-2.py

 

def getfunctionbyname(module_name, function_name):
    module = __import__(module_name)
    return getattr(module, function_name)

print(repr(getfunctionbyname("test-plugin", "hello")))

 


你也可以使用这个函数实现延迟化的模块导入 (lazy module loading). 例如在 [Example 1-7 #eg-1-7] 中
的 ``string`` 模块只在第一次使用的时候导入.

====Example 1-7. 使用 _ _import_ _ 函数实现 延迟导入====[eg-1-7]

File: builtin-import-example-3.py

 

class LazyImport:
    def __init__(self, module_name):
        self.module_name = module_name
        self.module = None
    def __getattr__(self, name):
        if self.module is None:
            self.module = __import__(self.module_name)
        return getattr(self.module, name)

string = LazyImport("string")

print(string.ascii_lowercase)
 

结果:abcdefghijklmnopqrstuvwxyz

 

Python 也提供了重新加载已加载模块的基本支持. [Example 1-8 #eg-1-8 会加载 3 次 //hello.py// 文件.

====Example 1-8. 使用 reload 函数====[eg-1-8]

File: builtin-reload-example-1.py

 

import hello
import imp


imp.reload(hello)
imp.reload(hello)

 

结果:

hello again, and welcome to the show
hello again, and welcome to the show
hello again, and welcome to the show

 

reload 直接接受模块作为参数.

``` [!Feather 注:  ^ 原句无法理解, 稍后讨论.]

注意,当你重加载模块时, 它会被重新编译, 新的模块会代替模块字典里的老模块. 但是, 已经用原模块里的类建立的实例仍然使用的是老模块(不会被更新).

同样地, 使用 ``from-import`` 直接创建的到模块内容的引用也是不会被更新的.

 

 

好了,__buildin__的模块就学到这里,明天学习关于名称空间的模块

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics