
作者:天津九安特機電工程有限公司 來(lái)源: 天津九安特機電工程有限公司 日期:2026-05-04 17:58:15
Python的函數dir函(°o°)數用于返回對象的屬性和方法列表。
P(′?_?`)ython的函數dir(′ω`)()函數
dir()函??數是Python中的一個(gè)內置函數,用于返回一個(gè)( ???)包含指定(′?`*)對象的函數所有屬性和方法的列表,這個(gè)列表包含了對象的函數所有屬(′?ω?`)性、方法(′_ゝ`)以及從父類(lèi)繼承的函數屬性和方法,如果未指定對象,函數dir()函數將返回當前作用域內的函(′;ω;`)數所有名稱(chēng)。
dir()函數的基本語(yǔ)法如下:
dir([object])object是一個(gè)可選參數,表示要列出其屬性和方(??-)?法的函數對象(/ω\),如果不提供此參數,函數dir()函數將返回當前作用域內的函數所有名稱(chēng)。
1( ?ω?)、列出對象的函數屬性和方法
我們可以使用dir()函數來(lái)查看一個(gè)對象的所有屬性和方法,我們可以查看一個(gè)字符串對象的函數所??有屬性和方法:
print(dir("hello"))輸出結果:
['__add__', '__cl??ass__', '__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', 'co??unt', 'encode', 'endswith', 'expandtabs',?? 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'i(′?_?`)sprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower'??, 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split??', 'splitline??s', 'startswith', 'strip', 'swapcase', 'title', 'translate',(°ロ°) ! 'upper', 'zfill']
2、列出當前作??用域內的函數所有名稱(chēng)
如果我們不提供參數給dir()函數,它將返回當前作用域內的所有名稱(chēng):
def my_function(): a = 1 b = 2 c = 3 print(dir())my_function()輸出結果(可能因環(huán)境而異):
['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'my_function', 'a', 'b', 'c']1、如何使用dir()函數查找一個(gè)對象的所有屬性和方法?
答:直接調用dir()函數并傳入對象作為參數即可。dir(my_object)。
2、dir()函數返回的列表中(zhong)包含哪些類(lèi)型的成員?
答:dir()函數返回的列表包含了對象的所有屬性、方法以及從父類(lèi)繼承的屬性和方法。
3、如何查看當前作用域內的所有名稱(chēng)?
答:直接調用dir()函數,不需要傳入參數。dir()。
4、dir()(′?`)函數和vars()函數有什么區別?