对象自省
自省在计算机编程领域里,是指在运行时判断一个对象的类型和能力。
dir
能够返回一个列表,列举了 一个对象所拥有的属性和方法。
my_list = [1,2,3]
print(dir(my_list))
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
"""
这有助于我们寻找方法。
type
返回一个对象的类型。
print(type(""))
print(type([]))
print(type({}))
print(type(dict))
print(type(3))
"""
"""
id
返回任意不同种类对象的唯一ID
name = "Yasoob"
print(id(name))
inspect
inspect模块提供了很多有用的函数,来获取活跃对象的信息
import inspect
print(inspect.getmembers(str))
"""
[('__add__', ), ('__class__', ), ('__contains__', ), ('__delattr__', ), ('__dir__', ), ('__doc__', "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."), ('__eq__', ), ('__format__', ), ('__ge__', ), ('__getattribute__', ), ('__getitem__', ), ('__getnewargs__', ), ('__gt__', ), ('__hash__', ), ('__init__', ), ('__init_subclass__', ), ('__iter__', ), ('__le__', ), ('__len__', ), ('__lt__', ), ('__mod__', ), ('__mul__', ), ('__ne__', ), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__rmod__', ), ('__rmul__', ), ('__setattr__', ), ('__sizeof__', ), ('__str__', ), ('__subclasshook__', ), ('capitalize', ), ('casefold', ), ('center', ), ('count', ), ('encode', ), ('endswith', ), ('expandtabs', ), ('find', ), ('format', ), ('format_map', ), ('index', ), ('isalnum', ), ('isalpha', ), ('isascii', ), ('isdecimal', ), ('isdigit', ), ('isidentifier', ), ('islower', ), ('isnumeric', ), ('isprintable', ), ('isspace', ), ('istitle', ), ('isupper', ), ('join', ), ('ljust', ), ('lower', ), ('lstrip', ), ('maketrans', ), ('partition', ), ('replace', ), ('rfind', ), ('rindex', ), ('rjust', ), ('rpartition', ), ('rsplit', ), ('rstrip', ), ('split', ), ('splitlines', ), ('startswith', ), ('strip', ), ('swapcase', ), ('title', ), ('translate', ), ('upper', ), ('zfill', )]
"""