3 回答
TA貢獻1963條經驗 獲得超6個贊
您可以使用內置dir()函數來獲取模塊具有的所有屬性的列表。在命令行上嘗試此操作以查看其工作原理。
>>> import moduleName
>>> dir(moduleName)
另外,您可以使用該hasattr(module_name, "attr_name")函數來查找模塊是否具有特定屬性。
TA貢獻1946條經驗 獲得超3個贊
我相信您想要的是這樣的:
來自對象的屬性列表
以我的拙見,內置功能dir()可以為您完成這項工作。取自help(dir)Python Shell上的輸出:
目錄(...)
dir([object]) -> list of strings
如果不帶參數調用,則返回當前作用域中的名稱。
否則,返回按字母順序排列的名稱列表,該列表包含給定對象的(某些)屬性以及從中可以訪問的屬性。
如果該對象提供了名為的方法__dir__,則將使用該方法;否則,將使用該方法。否則,將使用默認的dir()邏輯并返回:
對于模塊對象:模塊的屬性。
對于一個類對象:其屬性,以及遞歸其基類的屬性。
對于任何其他對象:其屬性,其類的屬性,以及遞歸地為其類的基類的屬性。
例如:
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
在檢查您的問題時,我決定展示自己的思路,并以更好的格式輸出dir()。
dir_attributes.py(Python 2.7.6)
#!/usr/bin/python
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print "\nObject Data: %s" % obj
print "Object Type: %s\n" % type(obj)
for method in dir(obj):
# the comma at the end of the print, makes it printing
# in the same line, 4 times (count)
print "| {0: <20}".format(method),
count += 1
if count == 4:
count = 0
dir_attributes.py(Python 3.4.3)
#!/usr/bin/python3
""" Demonstrates the usage of dir(), with better output. """
__author__ = "ivanleoncz"
obj = "I am a string."
count = 0
print("\nObject Data: ", obj)
print("Object Type: ", type(obj),"\n")
for method in dir(obj):
# the end=" " at the end of the print statement,
# makes it printing in the same line, 4 times (count)
print("| {:20}".format(method), end=" ")
count += 1
if count == 4:
count = 0
print("")
希望我有所貢獻:)。
添加回答
舉報
