在Python中,存取器和修改器方法用於存取類別的私有數據,這些資料無法從類別外部存取。在物件導向程式設計中,類別物件的資料被封裝,也就是物件資料被保持為私有數據,無法從物件外部存取。使用Python中的存取器和修改器方法提供對這些私有資料的存取。這些方法在Python中也被稱為getter和setter方法。在本文中,我們將透過範例來理解存取器和修改器方法。
存取器方法用於存取物件資料。可以使用存取器方法存取物件的私有變數。存取器方法被宣告為公共方法,用於傳回物件的私有成員資料。存取器方法也被稱為getter方法,因為它們用於獲取物件資料。
In Python the accessor method is defined using @property decorator. When the accessor method is called it returns the private member variable value of the object.
在下面的範例中,我們將定義一個名為Person的類,其中包含一個私有變數_name。然後,我們建立一個名為name的存取器方法,該方法傳回Person類別的私有成員變數_name的值。我們可以透過建立person物件並使用name存取器方法來存取_name屬性的值。
class Person: def __init__(self, name): self.__name = name @property def name(self): return self.__name person = Person("John") print(person.name)
John
Mutator methods are used to modify an object's private data. Mutator methods are also called setter methods as they are used to set/modify the value of an object private private private the value private private private privvate privvate privvate privvate privvate privvate privvate privvated privvated privvated privvate」prive private privvate privvates privvated privvated privvated privperd privvated privvated privvated privvated privvated privvated 商店》 ject variables.
In python mutator methods are defined using the @
class Person: def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value person = Person("John") person.name = "Jane" print(person.name)
輸出
Jane
以上是在Python中的訪問器和修改器方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!