Menu Close

Python 的 dir()内置函数

dir() 是 Python3 中一个强大的内置函数,它返回任何对象的属性的列表(比如函数、模块、字符串、列表、字典等). dir()是python的内置函数,用于列出对象的所有属性。在python中,一切皆对象。模块也不例外。因此可以使用dir()查看模块都有哪些属性。

python 内置函数dir()
python 内置函数dir()

语法 :

dir({object})

参数

object [optional] : Takes object name

dir() 尝试返回调用它的对象的有效属性列表。此外,dir() 函数对不同类型的对象的行为也大不相同,因为它旨在生成最相关的对象,而不是完整的信息。

  • 对于类对象,它还返回所有有效属性和基本属性的名称列表。
  • 对于 Modules/Library 对象,它会尝试返回包含在该模块中的所有属性的名称列表。
  • 如果未传递任何参数,则返回当前本地范围内的名称列表。

例1.dir显示内置函数的列表

# Python code to demonstrate dir()
# when no parameters are passed

# Note that we have not imported any modules
print(dir())


# Now let's import two modules
import random
import math

# return the module names added to
# the local namespace including all
# the existing ones as before
print(dir())

结果:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'random']

例2.1  dir(random)的结果

# Python3 code to demonstrate dir() function
# when a module Object is passed as parameter.

# import the random module
import random

# Prints list which contains names of
# attributes in random function
print("The contents of the random library are::")

# module Object is passed as parameter
print(dir(random))

The contents of the random library are::

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_index', '_inst', '_isfinite', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

例3.把对象作为参数

# When a list object is passed as
# parameters for the dir() function

# A list, which contains
# a few random values
com2743 = ["tutorial", "gfg", "Computer Science",
"Data Structures", "Algorithms"]

# dir() will also list out common
# attributes of the dictionary
d = {} # empty dictionary

# dir() will return all the available
# list methods in current local scope
print(dir(com2743))

# Call dir() with the dictionary
# name "d" as parameter. Return all
# the available dict methods in the
# current local scope
print(dir(d))

结果:

['__add__', '__class__', '__class_getitem__', '__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']
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

dir()的使用:

1.无参情况下使用,返回当前作用域属性名称。

2.有参情况下,返回sys模块的所有属性。

3.对象提供了__dir__()方法,则按__dir__返回:

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in Python教程

Related Posts