Python类的Getter/Setters方法是什么

Python类的Getter/Setters方法是什么

在Python中,我们有不同的方法可以让我们的工作变得非常简单和容易。在Python中,我们有两种方法,即getter和setter。这些方法在Python的面向对象编程语言中起着重要的作用,可以隐藏私有变量。

Python中的这些方法与其他面向对象编程语言中的getter/setter方法不同。它们用于数据封装的面向对象编程语言。它们用于以下条件:

  • 在Python中,getter/setter用于验证获取和设置值的逻辑。

  • 为了避免外部用户直接访问隐藏变量,或者可以说是为了避免外部用户修改或访问隐藏变量,我们使用getter和setter。

  • 数据封装将与特定方法相关的数据绑定在一起。通过使用这种格式,数据的修改和访问将受到限制。

  • 我们可以通过使用getter和setter方法来实现Python中的数据封装。

  • 在Python中使用getter和setter的方式并不那么容易。要使用getter方法获取一个值,我们必须使用get(),要使用setter方法设置一个值,我们必须使用set()。

  • getter方法允许访问私有属性,而setter方法用于设置属性的值。

示例

让我们看一个例子来理解Python中的getter和setter方法。下面的代码可以用来使用getter和setter方法。

  • 首先,在代码中我们创建了一个名为Tutorialspoint的类。接下来,在类内部我们使用 __init__ 函数初始化了这个类。

  • 然后,为了定义getter方法,我们创建了一个名为 get_name 的函数。

  • 接下来,为了定义 setter方法 ,我们创建了一个名为 set_name 的函数。现在我们调用Tutorialspoint类,并将其分配给变量b。

  • 接下来,我们使用setter方法将值python设置为类b的值,我们使用 set_name 函数并与python一起使用。

  • 接下来,为了使用getter方法,我们打印了类b的 get_name() 函数。然后也打印了 _name变量。

class Tutorialspoint:   
   def __init__(self, name = 0):   
      self._name = name   
      # using the getter method   
   def get_name(self):   
      return self._name   
      # using the setter method   
   def set_name(self, a):   
      self._name = a   

b = Tutorialspoint()   

#using the setter function  
b.set_name("Python")   

# using the getter function  
print(b.get_name())   

print(b._name)

输出

以下是Python面向对象编程语言中getter和setter方法的使用输出。

Python
Python

示例

让我们看一个更好理解Python中getter和setter方法的例子。以下代码可以用于使用getter和setter方法。

class python:   
   def __init__(self, x = 0):   
      self._x = x   
      # using the getter method   
   def get_x(self):   
      return self._x   
      # using the setter method   
   def set_x(self, a):   
      self._x = a   

b = python()   

#using the setter function  
b.set_x([100,200])   

# using the getter function  
print(b.get_x())   

print(b._x)

输出

[100, 200]
[100, 200]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程