【Python】【基础知识】【内置函数】【dir的使用方法】

原英文帮助文档:

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__().

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module’s attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir()   # show the names in the module namespace  # doctest: +SKIP
[‘__builtins__‘, ‘__name__‘, ‘struct‘]
>>> dir(struct)   # show the names in the struct module # doctest: +SKIP
[‘Struct‘, ‘__all__‘, ‘__builtins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘,
 ‘__initializing__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘,
 ‘_clearcache‘, ‘calcsize‘, ‘error‘, ‘pack‘, ‘pack_into‘,
 ‘unpack‘, ‘unpack_from‘]
>>> class Shape:
...     def __dir__(self):
...         return [‘area‘, ‘perimeter‘, ‘location‘]
>>> s = Shape()
>>> dir(s)
[‘area‘, ‘location‘, ‘perimeter‘]

Note

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

————————(我是分割线)————————

中文解释:

不带参数,返回当前本地作用域的名称列表。

>>> dir()
[‘__annotations__‘, ‘__builtins__‘, ‘__doc__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘, ‘__spec__‘]
>>> 

使用参数,尝试返回该对象的有效属性列表。

>>> a = "string"
>>> dir(a)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__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‘]
>>>
>>> dir(str)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__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‘]
>>>
>>> 

如果对象有一个名字叫__dir__()  的方法(函数),则将调用此方法,并且必须返回属性列表。

(大多数常见对象都有__dir__()方法  )

这允许实现自定义__getattr__() 或 __getattribute__()函数的对象自定义dir()报告其属性的方式。

如果对象不提供__dir__() ,则函数将尽力从对象的__dict__ 属性(如果其已经从类型对象手机信息去定义的话)

结果列表不一定完整,并且在对象具有自定义的__getattr__()时可能不准确。

默认的dir()机制,对不同类型的对象的行为不同,因为它试图生成最相关而不是最完整的信息。

如果对象是模块,则列表包含模块属性的名称。

如果对象是类型或类对象,则列表包含其属性的名称,并递归地包含其基的属性的名称。否则列表将包含对象的属性名、类的属性名,以及类的基类的递归属性名。

结果列表按字母顺序排序,如:

>>> import struct
>>> dir()   # show the names in the module namespace  # doctest: +SKIP
[‘__builtins__‘, ‘__name__‘, ‘struct‘]
>>> dir(struct)   # show the names in the struct module # doctest: +SKIP
[‘Struct‘, ‘__all__‘, ‘__builtins__‘, ‘__cached__‘, ‘__doc__‘, ‘__file__‘,
 ‘__initializing__‘, ‘__loader__‘, ‘__name__‘, ‘__package__‘,
 ‘_clearcache‘, ‘calcsize‘, ‘error‘, ‘pack‘, ‘pack_into‘,
 ‘unpack‘, ‘unpack_from‘]
>>> class Shape:
...     def __dir__(self):
...         return [‘area‘, ‘perimeter‘, ‘location‘]
>>> s = Shape()
>>> dir(s)
[‘area‘, ‘location‘, ‘perimeter‘]

备注:

因为提供dir()主要是为了方便在交互提示下使用,因此它试图提供一组有趣的名称,而不是提供一组严格或一致定义的名称,并且其详细行为可能会在不同版本中发生变化。

例如当参数是类时,元类属性不在结果列表属性中。

———————(我是分割线)————————

————————(我是分割线)————————

参考:

1. Python 3.7.2 documentation

2. RUNOOB.COM:https://www.runoob.com/python/python-func-dir.html

备注:

初次编辑时间:2019年9月21日22:06:44

第一次修改时间:2019年9月21日22:10:14   / 添加环境信息

环境:Windows 7   / Python 3.7.2

原文地址:https://www.cnblogs.com/kaixin2018/p/11565094.html

时间: 2024-07-29 02:36:08

【Python】【基础知识】【内置函数】【dir的使用方法】的相关文章

python基础知识内置函数(二)、装饰器

一.内置函数 1.chr()  ord() r= chr(65) #ASCII对应的字母 print (r) n= ord("a") #ASCII对应的数字 print(n) #以下为执行结果 A 97 可以利用此函数随机生成验证码: import random li=[] for i in range(6): r = random.randrange(0,5) if r ==2 or r==4: num = random.randrange(0,10) li.append(str(n

第六篇:python基础_6 内置函数与常用模块(一)

本篇内容 内置函数 匿名函数 re模块 time模块 random模块 os模块 sys模块 json与pickle模块 shelve模块 一. 内置函数 1.定义 内置函数又被称为工厂函数. 2.常用的内置函数 (1)abs() #!/usr/binl/env python #encoding: utf-8 #author: YangLei print(abs(-1)) (2)all() #!/usr/binl/env python #encoding: utf-8 #author: Yang

Python基础day-11[内置函数(未完),递归,匿名函数]

内置函数: abs() : 返回数字的绝对值.参数可以是整数或浮点数,如果参数是复数,则返回复数的模. print(abs(0.2)) print(abs(1)) print(abs(-4)) print(abs(-0.2)) print(abs(3+4j)) 执行结果: D:\Python\Python36-32\python.exe E:/Python/DAY-11/tmp.py 0.2 1 4 0.2 5.0 Process finished with exit code 0 all():

python 基础 学习 内置函数

内置函数       例:如果返回数字的绝对值 ,写函数是非常不方便的 [[email protected] tools]# python fa.py  10 [[email protected] tools]# cat fa.py  #!/usr/bin/python def a(x):     if x < 0 :         return -x      return x  n = a(-10) print n  #帮助查看# >>> help(len) 用法: help

Python 基础5:内置函数一

===========内置函数=========== 1.abs绝对值 #abs() i = abs(-123) print(i) #结果:123 2.all与any #all 循环参数,如果每个元素都为真,那么all的返回值为真 #any,只要有一个是真的,则为真 r = all([True,True,False]) print(r) #结果:False #元素为假的有:0,None,空的字符串.列表.元组.字典 3.ascii,对象的类中找__repr__,获取齐返回值 # class Fo

python基础学习-内置函数

#!/usr/bin/env python # -*- coding:utf-8 -*- 系统内置函数 n =abs(-1) #绝对值 print(n) #bytes()函数 s="离开" re= bytes(s,encoding="utf-8")  # bytes() 把字符串 转换成字节 print(re) res = str(re,encoding="utf-8") #转换回字符串 print(res) re= bytes(s,encodi

Python基础编程 内置函数

内置函数 内置函数(一定记住并且精通) print()屏幕输出 int():pass str():pass bool():pass set(): pass list() 将一个可迭代对象转换成列表 tuple() 将一个可迭代对象转换成元组 dict() 通过相应的方式创建字典. # 创建字典的几种方式 #直接创建 dic = {1: 2} #字典推导式 print({i: 1 for i in range(3)}) dict() #dict创建 dic = dict(one=1, two=2,

学习PYTHON之路, DAY 4 - PYTHON 基础 4 (内置函数)

注:查看详细请看https://docs.python.org/3/library/functions.html#next 一 all(), any() False: 0, Noe, '', [], {}, () all()  全部为真是, 才为真 any() 任何一个为真, 都为真 二 bin(), oct(),hex() bin(), 接收十进制转二进制 (0b) oct(), 接收十进制转八进制 (0o) hex(), 接收十进制转十六进制 (0x) 三 bytes() bytes(只要转

python基础:内置函数zip,map,filter

一.zip zip,就是把俩list,合并到一起,如果想同时循环2个list的时候,可以用zip,会帮你轮流循环两个list 比如: l1=[1,2,3,4,5] l2=['a','b','c','d','e'] for a,b in zip(l1,l2): print(a,b) #得到的结果就是1 a2 b3 c4 d5 e 如果两个list的长度不一致,则以长度小的为依据 比如: l1=[1,2,3,4] l2=['a','b','c','d','e'] for a,b in zip(l1,

python之路——内置函数与匿名函数

内置函数 python里的内置函数.截止到python版本3.6.2,现在python一共为我们提供了68个内置函数.它们就是python提供给你直接可以拿来使用的所有函数.这些函数有些我们已经用过了,有些我们还没用到过,还有一些是被封印了,必须等我们学了新知识才能解开封印的.那今天我们就一起来认识一下python的内置函数.这么多函数,我们该从何学起呢? 上面就是内置函数的表,68个函数都在这儿了.这个表的顺序是按照首字母的排列顺序来的,你会发现都混乱的堆在一起.比如,oct和bin和hex都