Python中dir()函數是一個非常常用的函數,它的主要作用是返回一個列表,其中包含了一個模塊、類或實例所包含的所有屬性和方法。在Python中,屬性和方法都被視為對象的變量和函數,可以被直接調用或設置。
一、基本用法
dir()函數可以無參數調用,此時它會返回當前作用域內的所有變量、函數、類等信息,並且根據字母順序進行排序:
# 基本用法示例
def test_func():
pass
test_var = 1
print(dir())
輸出結果如下所示,其中__builtins__代表Python的內建模塊,而其他的變量、函數則是當前作用域內的:
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'test_func', 'test_var']
除了無參數調用外,dir()函數還可以接受一個參數,此時它會返回該參數所代表的對象的所有屬性和方法:
# 帶參用法示例
import math
print(dir(math))
輸出結果如下所示,其中包含了math模塊的所有屬性和方法:
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
二、特殊方法和屬性
在Python中,一些特殊的方法和屬性以特殊字符(如下劃線)開頭和結尾,例如__init__方法、__str__方法等。這些方法和屬性是Python提供的對類和對象進行特殊處理的機制,因此在使用dir()函數時,如果希望查看某個對象的特殊方法和屬性,需要使用特殊方法__dir__():
# 特殊方法和屬性示例
class MyClass:
def __init__(self):
self.x = 1
def __str__(self):
return str(self.x)
obj = MyClass()
print(dir(obj)) # 查看對象的所有方法和屬性
print(obj.__dir__()) # 查看對象的特殊方法和屬性
輸出結果如下所示,其中包含了特殊方法和屬性:
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'x']
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'x']
三、自定義列表屬性和方法
除了可以直接使用Python提供的方法和屬性外,在程序中也可以自定義類的屬性和方法。對於自定義屬性和方法,同樣可以使用dir函數查看:
# 自定義列表屬性和方法示例
class MyList(list):
def get_first(self):
return self[0]
my_list = MyList([1, 2, 3])
print(dir(my_list))
輸出結果如下所示,其中包含了自定義的屬性和方法:
['__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', 'get_first', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
四、總結
在Python中,dir()函數是一個非常常用的函數,它可以幫助我們了解一個模塊、類或實例所具有的所有屬性和方法,方便代碼編寫和調試。我們可以通過無參數調用或接受一個參數的方式來使用dir()函數,還可以使用特殊方法__dir__()來查看對象的特殊方法和屬性。此外,我們也可以在自定義類中添加屬性和方法,同樣可以使用dir()函數來查看自定義類的屬性和方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/187904.html