當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python dir()用法及代碼示例


dir()是Python3中強大的內置函數,它返回任何對象的屬性和方法的列表(例如函數,模塊,字符串,列表,字典等)。

用法:

dir({object})

參數:


object [optional]:Takes object name

返回:

dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information.

  • For Class Objects, it returns a list of names of all the valid attributes and base attributes as well.
  • For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module.
  • If no parameters are passed it returns a list of names in the current local scope.


代碼1:有和沒有導入外部庫。

# Python3 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())

輸出:


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



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


代碼2:

# 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 random library are::") 
  
# module Object is passed as parameter 
print(dir(random))

輸出:

The contents of random library are::

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',
'_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp',
'_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss',
'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', '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 conatains 
# a few random values 
geeks = ["geeksforgeeks", "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(geeks)) 
  
  
# 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__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', 
'__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__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', 
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', 
'__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']


代碼4:用戶定義的-具有可用__dir()__方法的類對象作為參數傳遞。

# Python3 program to demonstrate working 
# of dir(), when user defined objects are 
# passed are parameters. 
  
  
# Creation of a simple class with __dir()__ 
# method to demonstrate it's working 
class Supermarket:
  
    # Function __dir()___ which list all  
    # the base attributes to be used. 
    def __dir__(self):
        return['customer_name', 'product', 
               'quantity', 'price', 'date'] 
  
  
# user-defined object of class supermarket 
my_cart = Supermarket() 
  
# listing out the dir() method 
print(dir(my_cart))

輸出:

['customer_name', 'date', 'price', 'product', 'quantity']


應用範圍:

  • dir()有自己的一套用途。它通常用於簡單的日常程序中的調試目的,甚至在由開發人員團隊承擔的大型項目中也是如此。 dir()列出列出傳遞的參數的所有屬性的函數,在分別處理許多類和函數時確實非常有用。
  • dir()函數還可以列出模塊/列表/字典的所有可用屬性。因此,它還為我們提供了有關可用列表或模塊可以執行的操作的信息,當對模塊的了解很少甚至根本沒有信息時,這將非常有用。它還有助於更快地了解新模塊。


相關用法


注:本文由純淨天空篩選整理自retr0大神的英文原創作品 Python | dir() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。