[Python基礎]使用 dir() 函式獲取物件的所有屬性和方法

2024/01/27閱讀時間約 3 分鐘

Python 中,dir() 函式用於列舉對象的所有屬性方法。這包括對象的內建屬性方法以及自定義的屬性方法。以下是一個簡單的示例:

列舉所有屬性與方法

class MyClass:
def __init__(self):
self.attribute1 = 42
self.attribute2 = "Hello"

def method1(self):
print("This is method 1.")

def method2(self):
print("This is method 2.")

# 創建類的實例
my_instance = MyClass()

# 使用 dir() 獲取物件的所有屬性和方法
all_attributes = dir(my_instance)

# 打印所有屬性和方法
for attribute in all_attributes:
print(attribute)
# 印出的結果​
__class__
__delattr__
__dict__
__dir__
__doc__
__eq__
__format__
__ge__
__getattribute__
__gt__
__hash__
__init__
__init_subclass__
__le__
__lt__
__module__
__ne__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
__weakref__
attribute1
attribute2
method1
method2

在這個例子中,dir(my_instance) 會返回一個包含 my_instance 所有屬性的列表。這個列表包括類定義中的所有成員,無論是屬性還是方法。你可以使用這種方式來查看類的所有屬性。

注意:dir() 會列出所有屬性,包括一些由Python解釋器生成的特殊屬性,這可能包含你並未明確定義的一些東西。

模組和包的探索:

在模組或包的上下文中使用 dir() 可以查看其內容,包括所有可用的函式、類、變數等。

import math

# 查看 math 模組的所有屬性和方法
print(dir(math))

獲取當前作用域的變數名稱:

在函式或模組中使用 dir() 可以列舉當前作用域的所有變數名稱。

def my_function():
local_variable = 42
print(dir())

my_function() # 輸出 ['local_variable']

查看內建名稱:

在沒有提供對象的情況下,dir() 會返回內建名稱的列表。

x = 1
print(dir())


dir() 是一個多功能的工具對於探索了解程式碼中可用的元素非常有用。當你需要查看對象的結構、模組的內容或者作用域中的變數時。


某一天在在用nivision套件時,不知道出來的結果有什麼內容,就查到可以用dir()來查詢有包含什麼屬性跟方法,特地紀錄一下。


49會員
88內容數
Python程式設計師,不是在學習就是在學習的路上
留言0
查看全部
發表第一個留言支持創作者!