您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/3/16 22:50:01发布24次查看
在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.__nameperson = person(john)print(person.name)
输出john
mutator methodmutator 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 = valueperson = person(john)person.name = janeprint(person.name)
输出jane
conclusion访问器和修改器方法在面向对象编程中用于提供对对象的私有变量的访问。这些方法也被称为getter和setter方法,因为它们分别用于获取和设置/修改对象的私有变量。在python中,访问器和修改器方法分别使用@property和@a1e17fc95f63aad97bd44b139c2fb407.setter装饰器来定义。
以上就是在python中的访问器和修改器方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product