自省
什么是自省?
自省通过一定的机制让对象访问到自己的内部结构(属性)
常见的自省方法?
- obj.__dict__
- dir([object])
- getattr
- hasattr
- delattr
- inspect
__dict__
In [2]: class A:
...: name = 'Da'
...: def __init__(self, tag):
...: self.tag = tag
...:
In [7]: A.__dict__
Out[7]:
mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>,
'__doc__': None,
'__init__': <function __main__.A.__init__(self, tag)>,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'A' objects>,
'name': 'Da'})
dir
In [8]: dir(A)
Out[8]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'name']
相关问题
为什么dict中看不到的属性,通过obj.attr获取到? 如下
In [2]: class A:
...: name = 'Da'
...: def __init__(self, tag):
...: self.tag = tag
...:
In [3]: a = A('Ha')
In [4]: a.tag
Out[4]: 'Ha'
In [5]: a.__dict__
Out[5]: {'tag': 'Ha'}
In [6]: a.name
Out[6]: 'Da'