卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

在Python中的访问器和修改器方法

在Python中的访问器和修改器方法

在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.

Example

的中文翻译为:

示例

在下面的示例中,我们将定义一个名为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 Method

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 variable. Mutator methods are declared private which modifies the private value of the object variables.

In python mutator methods are defined using the @.setter decorator which specifies that the particular method behaves like a setter method. When the mutator method is called it sets the value of the object private variable.

Example

的中文翻译为:

示例

在下面的示例中,我们定义了一个Person类,该类具有一个私有的_name变量。我们还使用@property和@name.setter装饰器分别定义了一个名为name的访问器方法和一个名为name的修改器方法。当调用该函数并传递一个值参数时,name修改器方法会修改_name变量的值。

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

Conclusion

访问器和修改器方法在面向对象编程中用于提供对对象的私有变量的访问。这些方法也被称为getter和setter方法,因为它们分别用于获取和设置/修改对象的私有变量。在Python中,访问器和修改器方法分别使用@property和@<variable_name>.setter装饰器来定义。

卓越飞翔博客
上一篇: 如何使用PHP实现文件备份功能
下一篇: PHP和Xvfb的使用方法
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏