python笔记(五) - 获取对象的引用

1,使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。

>>> li = ["Larry""Curly"]
>>> li.pop
<built-in method pop of list object at 0x00A75850>
>>> getattr(li,'pop')
<built-in method pop of list object at 0x00A75850>
>>> getattr(li,'append')('Moe')
>>> li
[
'Larry''Curly''Moe']
>>> getattr((), "pop")

Traceback (most recent call last):
  File 
"<pyshell#29>", line 1in <module>
    getattr((), 
"pop")
AttributeError: 
'tuple' object has no attribute 'pop'
>>> 

 你不信都不行,getattr返回的就是一个方法

看这行:getattr(li,'append')('Moe')返回list的append方法后就直接调用这个方法将'Moe'加入li中

 

2,getattr还可以用于模块

>>> import string
>>> getattr(string,'join')
<function join at 0x00C0D9B0>
>>> string.join
<function join at 0x00C0D9B0>
>>> type(getattr(string,'join'))
<type 'function'>
>>> 

 getattr(string,'join')返回的就是函数,这里得到了验证,并且是可调用的

posted @ 2009-04-15 18:02  ________囧丶殇  阅读(210)  评论(0编辑  收藏  举报