您的位置:首页 > 编程语言 > Python开发

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

2009-04-15 18:02 330 查看
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 1, in <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')返回的就是函数,这里得到了验证,并且是可调用的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: