Python3.6内置函数(16)——dir()

浏览: 1429

英文文档

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

dir()

1、当不传参数时,返回当前作用域内的变量、方法和定义的类型列表。

>>> dir()
['A', '__annotations__', '__builtins__', '__doc__', '__loader__',
'__name__', '__package__', '__spec__', 'a', 'code1', 'code2',
'code3', 'compile1', 'compile2', 'compile3', 'i', 'name']
>>> B = '12345' #定义变量B
>>> dir()    #多了一个变量B
['A', 'B', '__annotations__', '__builtins__', '__doc__',
'__loader__', '__name__', '__package__', '__spec__', 'a',
'code1', 'code2', 'code3', 'compile1', 'compile2', 'compile3', 'i', 'name']


2、当参数对象是模块时,返回模块的属性、方法列表。

>>> import math
>>> math
<module 'math' (built-in)>
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']


3、当参数对象是类时,返回类及其子类的属性、方法列表。

>>> class A:
      name = 'class'
>>> a = A()
>>> dir(a) #name是类A的属性,其他则是默认继承的object的属性、方法
['__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__', 'name']


4、当对象定义了__dir__方法,则返回__dir__方法的结果

>>> class B:
      def __dir__(self):
            return ['name','age']
>>> b = B()
>>> dir(b) #调用 __dir__方法
['age', 'name']

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,希望你留言和我进行交流、讨论。

欢迎关注微信公众号,访问更多精彩:数据之魅

如需转载,请联系授权,谢谢合作。

火狐截图_2019-06-29T07-07-45.688Z.png

推荐 0
本文由 Airy 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册