Python中的访问器和修改器方法
在Python中,类是用户定义类型的对象的原型。它指定并定义了相同类型的对象,一个类包括一组数据和方法定义。此外,对象是类的单个实例,但您可以从单个类创建多个对象。
注意:有关详细信息,请参阅Python类和对象
Accessor 和 Mutator 方法
因此,你们都必须熟悉对象的内部数据必须保密这一事实。但是类接口中应该有一些方法可以允许对象的用户以平静的方式访问和更改数据(存储在内部)。因此,对于这种情况,我们有两种方法,即Accessors和Mutators ,它们分别有助于访问和更改内部存储的数据。
- Accessor Method:该方法用于访问对象的状态,即可以通过该方法访问隐藏在对象中的数据。但是,这种方法不能改变对象的状态,它只能访问隐藏的数据。我们可以用get来命名这些方法。
- Mutator Method:此方法用于改变/修改对象的状态,即改变数据变量的隐藏值。它可以立即将变量的值设置为新值。此方法也称为更新方法。此外,我们可以用set来命名这些方法。
下面的示例说明了Python中Accessor 和 Mutator方法的使用:
示例 1:
Python
# Python program to illustrate the use of
# Accessor and Mutator methods
# importing "array" for array operations
import array
# initializing array with array values
# initializes array with signed integers
arr = array.array('i', [5, 1, 3, 4, 2, 2, 7])
# Accesses the index of the value in argument
print (arr.index(2))
# Accesses the number of time the
# stated value is present
print (arr.count(2))
# Mutates the array list
(arr.append(19))
# Prints the array after alteration
print (arr)
Python
# Python program to illustrate the use of
# Accessor and Mutator methods
# Defining class Car
class Car:
# Defining method init method with a parameter
def __init__(self, carname):
self.__make = carname
# Defining Mutator Method
def set_make(self, carname):
self.__make = carname
# Defining Accessor Method
def get_make(self):
return self.__make
# Creating an object
myCar = Car('Ford');
# Accesses the value of the variable
# using Accessor method and then
# prints it
print (myCar.get_make())
# Modifying the value of the variable
# using Mutator method
myCar.set_make('Porche')
# Prints the modified value
print (myCar.get_make())
输出:
4
2
array('i', [5, 1, 3, 4, 2, 2, 7, 19])
所以,这里的index()和count()方法只访问数据,所以它们是访问器方法,但是这里的append()方法修改了数组,所以它是一个 mutator 方法。
示例 2:
Python
# Python program to illustrate the use of
# Accessor and Mutator methods
# Defining class Car
class Car:
# Defining method init method with a parameter
def __init__(self, carname):
self.__make = carname
# Defining Mutator Method
def set_make(self, carname):
self.__make = carname
# Defining Accessor Method
def get_make(self):
return self.__make
# Creating an object
myCar = Car('Ford');
# Accesses the value of the variable
# using Accessor method and then
# prints it
print (myCar.get_make())
# Modifying the value of the variable
# using Mutator method
myCar.set_make('Porche')
# Prints the modified value
print (myCar.get_make())
输出:
Ford
Porche
因此,这里使用 Accessor 方法(即get_make )访问汽车的名称,然后使用 Mutator 方法(即set_make )对其进行修改。