|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一个账号 于 2020-3-23 11:18 编辑
Python dir() 函数
语法
- dir([object]) -> list of strings
复制代码
参数
返回值
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表。
带参数时,返回参数的属性、方法列表。
如果参数包含方法 __dir__(),该方法将被调用。
如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
例子
- >>> a = 3
- >>> def test():
- pass
- >>> locals()
- {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': 3, 'test': <function test at 0x000001915802B430>}
- >>> dir()
- ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'test']
- >>> class A:
- a = 3
- b = 4
- def __init__(self):
- self.abc = 3
- self.var = "test"
-
- >>> a = A()
- >>> dir(a)
- ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'abc', 'b', 'var']
- >>> class A:
- a = 3
- b = 4
- def __init__(self):
- self.abc = 3
- self.var = "test"
- def __dir__(self):
- return "__dir__"
-
- >>> a = A()
- >>> dir(a)
- ['_', '_', '_', '_', 'd', 'i', 'r']
- >>> dir(list) # 与 dir([]) 相同
- ['__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']
复制代码 |
|