python中的反射和自省

本文介绍了Python中的反射和自省。自省是对运行时对象进行检查,包括使用`dir()`、类型检查和`inspect`模块。反射则更进一步,能够动态设置属性,包括普通方法和类实例方法,并通过`getattr`及`__getattr__`进行操作。反射不仅能够检查,还能在运行时修改对象。
摘要由CSDN通过智能技术生成

Introspection

examine something, typically an object, at runtime.

dir()

dir(object)
['__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']

type checking

type(int)
type
int.__class__
type
isinstance(4, int)
True
issubclass(int, object)
True

inspect

import inspect
inspect.isclass(int)
True
def foo():
    '''foo comments'''
    pass
inspect.getsource(foo)
"def foo():\n    '''foo comments'''\n    pass\n"
[attr for attr in dir(inspect) if attr.startswith('is')]
['isabstract',
 'isasyncgen',
 'isasyncgenfunction',
 'isawaitable',
 'isbuiltin',
 'isclass',
 'iscode',
 'iscoroutine',
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值