本节是pythonbiaozhunku/ target=_blank class=infotextkey>python标准库的第一节。
1,使用字典或者元祖中的参数调用元素
复制代码 代码示例:
def function( a, b ):
print a, b
apply( function, ( 1, 2 ) )
apply( function, ( 1 , ), {"b":2} ) #注意这里的","
apply( function, (), {"a":1, "b":2} )
#apply 函数的一个常见用法是把
构造函数参数从子类传递到
2,函数需要接受很多参数时
复制代码 代码示例:
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 )
3,使用*a来表示元祖,**b来表示字典
复制代码 代码示例:
def function1( *a, **b ):
print a, b
apply( function1, ( 1, 2 ) )
apply( function1, ( 1, ), {"b":2} )
4,动态导入所以已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()
5,使用__import__导入特定的函数
复制代码 代码示例:
def getfunctionbyname( module_name, function_name ):
module = __import__( module_name )
return getattr( module, function_name )
print repr( getfunctionbyname( "dumbdbm", "open" ) )
6,使用__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 )