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')返回的就是函数,这里得到了验证,并且是可调用的
>>> 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')返回的就是函数,这里得到了验证,并且是可调用的
相关文章推荐
- python学习笔记---对象赋值其实就是引用
- 【Python】学习笔记——-7.4、获取对象信息
- 【Python学习笔记】面向对象编程:获取对象信息
- python学习笔记 获取对象信息
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- python学习笔记4(对象/引用;多范式; 上下文管理器)
- python学习笔记7:对象引用与对象
- Python通过getattr获取对象引用
- python 引用和对象理解
- Python脚本控制的WebDriver 常用操作 <十八> 获取测试对象的css属性
- Javascript下获取对象引用的两种方法之getElementsByTagName
- 【Python笔记】从一个“古怪”的case探究CPython对Int对象的实现细节
- python入门笔记-类和对象定义及调用
- 《简明 Python 教程》笔记-----面向对象及系统相关
- Python学习笔记4:一切皆对象,所有对象都是第一类的
- Python笔记(2):多参数,全局变量与局部变量,层状作用域,函数式编程,面向对象
- python 共享引用:多个变量引用同一对象
- python Class:获取对象类型
- Java基础入门笔记-对象与引用
- python对象引用引起的问题