python标准库学习1

时间:2022-09-01 21:39:04

本系列是本人学习python标准库的一些笔记,呵呵,此处由于时间的关系,只给出代码,至于运行结果我没有放上去,大家见谅。因为那个太麻烦了。

#-----使用字典或者元祖中的参数调用元素

def function( a, b ):
    print a, b

apply( function, ( 1, 2 ) )
apply( function, ( 1 , ), {"b":2} )   #注意这里的","
apply( function, (), {"a":1, "b":2} )

#apply 函数的一个常见用法是把构造函数参数从子类传递到

#函数需要接受很多参数的时候. 

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 ) 

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

  # 使用*a来表示元祖,**b来表示字典

def function1( *a, **b ):
    print a, b
apply( function1, ( 1, 2 ) )
apply( function1, ( 1, ), {"b":2} )

  #动态导入所以已plugin结尾的模块

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 
def hello():
    print "hello" 

for module in modules: 
    module.hello()

  # 使用__import__导入特定的函数

def getfunctionbyname( module_name, function_name ):
    module = __import__( module_name ) 
    return getattr( module, function_name ) 
 
print repr( getfunctionbyname( "dumbdbm", "open" ) ) 

  #使用__import__延迟导入需要的模块,比如第一次使用的时候才导入

class LazyImport:
    def __init__( self, moule_name ):
        self.moule_name = moule_name
        self.moule = None
    def __getattr__( self, name ):
        if self.moule is None:
            self.moule = __import__( self.moule_name )
        return getattr( self.moule, name ) 
    
string = LazyImport( "string" )
print string.lowercase

  

class A: 
    def a( self ): 
        pass 
    def b( self ): 
        pass 
 
class B( A ): 
    def c( self ): 
        pass 
    def d( self ): 
        pass 
 
def getmembers( klass, members = None ): 
    # get a list of all class members, ordered by class 
    if members is None: 
        members = [] 
    for k in klass.__bases__: 
        getmembers( k, members ) 
    for m in dir( klass ): 
        if m not in members: 
            members.append( m ) 
    return members 

print getmembers( A ) 
print getmembers( B ) 
print getmembers( IOError )