Python dir() 函式介紹

Python的dir()函式是一個非常有用的函式,它可以用來查看物件的屬性和方法。它可以用來查看模組、類別和實例的屬性和方法。

dir() 函式的基本用法

dir()函式的基本用法是將物件作為參數傳遞給它,它將會返回一個列表,其中包含該物件的屬性和方法。例如,如果我們想查看字串物件的屬性和方法,我們可以使用以下程式碼:

str_obj = "Hello World"
print(dir(str_obj))

輸出結果將會是一個列表,其中包含字串物件的屬性和方法:

['__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', '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()函式還可以接受一個可選的參數,該參數是一個字串,它可以用來指定要查看的屬性和方法的類型。例如,如果我們想查看字串物件的所有方法,我們可以使用以下程式碼:

str_obj = "Hello World"
print(dir(str_obj, "method"))

輸出結果將會是一個列表,其中只包含字串物件的方法:

['__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', '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']

總結

Python的dir()函式是一個非常有用的函式,它可以用來查看物件的屬性和方法。它可以接受一個可選的參數,該參數是一個字串,它可以用來指定要查看的屬性和方法的類型。它可以用來查看模組、類別和實例的屬性和方法,是一個非常有用的函式。

Categorized in:

Tagged in: