Python进阶 对象自省



自省(introspection),在计算机编程领域里,是指在运行时来判断一个对象的类型的能力。
它是Python的强项之一。Python中所有一切都是一个对象,而且我们可以仔细勘察那些对象。
Python还包含了许多内置函数和模块来帮助我们。



dir

dir用于自省的最重要的函数之一。
它返回一个列表,列出了一个对象所拥有的属性和方法。

my_list = [1, 2, 3]
dir(my_list)
# Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
# '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
# '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
# '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
# '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
# 'remove', 'reverse', 'sort']

上面的自省给了我们一个列表对象的所有方法的名字。
当你没法回忆起一个方法的名字,这会非常有帮助。
如果我们运行dir()而不传入参数,那么它会返回当前作用域的所有名字。

dir()
# ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'my_list']



type和id



type函数返回一个对象的类型。

print(type(''))
# Output: <type 'str'>

print(type([]))
# Output: <type 'list'>

print(type({}))
# Output: <type 'dict'>

print(type(dict))
# Output: <type 'type'>

print(type(3))
# Output: <type 'int'>



id()函数返回任意不同种类对象的唯一ID。

name = "Yasoob"
print(id(name))
# Output: 139972439030304


inspect模块

inspect模块也提供了许多有用的函数,来获取活跃对象的信息。

import inspect
print(inspect.getmembers(str))
# Output: [('__add__', <slot wrapper '__add__' of ... ...
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,239评论 4 16
  • 1.元类 1.1.1类也是对象 在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段。在Python中这...
    TENG书阅读 1,315评论 0 3
  • 内置函数Python解释器内置了许多功能和类型,总是可用的。他们是按字母顺序列在这里。 abs(x)返回一个数的绝...
    uangianlap阅读 1,272评论 0 0
  • “共眠一舸听秋雨,小簟轻衾各自寒”。【清】朱彝尊。描述的是和一个他深爱着但囿于现实而不能表达的女子。两人各眠一处但...
    静静在简书阅读 305评论 0 0
  • 2017年1月9日。今天早晨9点出发开车前往南靖县土楼景区。走高速,大约3个小时。要经过著名的海沧大桥,在飞机...
    北方的愔格阅读 1,187评论 7 5