Python中訪問例項變數的不同方法
例項變數通常用於表示物件的 狀態或屬性。類的每個例項都可以擁有自己的一組例項變數,這些變數可以儲存唯一的值。例項變數在類的 方法內定義,並在例項的生命週期內可訪問。
在Python中訪問例項變數
使用例項變數帶來的靈活性允許每個例項維護自己的一組變數,從而能夠為不同的物件啟用自定義行為和資料儲存。因此,在Python中訪問例項變數是一個有用的步驟。在Python中訪問例項變數有不同的方法,讓我們一一來看。
使用點表示法
可以使用**點表示法**以及例項名稱來訪問例項變數。這是訪問例項變數的一種簡單易用的方法。以下是使用點表示法的語法。
instance.variable_name
其中:
**instance** 是例項。
**variable_name** 是變數的名稱。
表示點表示法。
示例
在這個示例中,我們將使用點表示法從使用者定義的類中訪問例項變數,然後例項變數將作為輸出返回。
class sample_class: def __init__(self, variable): self.variable = variable instance = sample_class("Welcome to Tutorialspoint, Have a happy learning!") print(instance.variable)
輸出
以下是使用點表示法訪問例項變數的輸出。
Welcome to Tutorialspoint, Have a happy learning!
使用self關鍵字
在類中,**self** 關鍵字是例項的引用。可以使用 **self.variable_name** 訪問類中的例項變數。以下是使用self關鍵字訪問例項變數的語法。
self.variable_name
示例
如果要從定義的類中訪問例項變數,可以使用**self**關鍵字。
class sample: def __init__(self, variable): self.variable = variable def print_variable(self): print(self.variable) instance = sample("Welcome to Tutorialspoint, Have a happy learning!") instance.print_variable()
輸出
Welcome to Tutorialspoint, Have a happy learning!
使用__dict__屬性
在Python語言的每個例項中,都存在一個名為**__dict__** 的字典,它包含所有例項變數。因此,我們可以藉助__dict__屬性訪問例項變數。以下是使用__dict__屬性的語法。
instance.__dict__[variable_name]
示例
在這個示例中,我們將使用**__dict__** 屬性獲取類的例項變數。
class sample: def __init__(self, variable): self.variable = variable instance = sample("Python is one of the popular programming languages") print(instance.__dict__['variable'])
輸出
Python is one of the popular programming languages
使用getattr()函式
Python提供了一個名為**getattr()** 的內建函式,它接受兩個引數:一個物件和一個字串。此函式返回物件中指定屬性的值。以下是使用getattr()函式的語法。
getattr(instance, 'variable_name')
示例
如果要從使用者定義的類中獲取例項變數,則需要將例項和變數名稱傳遞給getattr()函式。
class sampe_class: def __init__(self, variable): self.variable = variable instance = sampe_class("Hello, Python is one of the popular programming languages!") print(getattr(instance, 'variable'))
輸出
Hello, Python is one of the popular programming languages!
使用hasattr()函式
hasattr()函式與**getattr()** 函式相同,但唯一的區別是hasattr()返回布林值True或False。如果類中存在該變數,則輸出將返回為True,否則返回為False。
語法
以下是使用**getattr()** 函式的語法。
hasattr(instance, 'variable_name')
示例
以下示例演示了使用**hasattr()** 函式獲取例項變數。
class sampe_class: def __init__(self, variable): self.variable = variable instance = sampe_class("Hello, Python is one of the popular programming languages!") print(hasattr(instance, 'variable'))
輸出
True