Getters(also known as 'accessors') and setters (aka. 'mutators') are used in many object oriented programming languages to ensure the principle of data encapsulation. Data encapsulation - as we have learnt in our introduction on Object Oriented Programming of our tutorial - is seen as the bundling of data with the methods that operate on them. These methods are of course the getter for retrieving the data and the setter for changing the data. According to this principle, the attributes of a class are made private to hide and protect them.
Unfortunately, it is widespread belief that a proper Python class should encapsulate private attributes by using getters and setters. As soon as one of these programmers introduces a new attribute, he or she will make it a private variable and creates "automatically" a getter and a setter for this attribute. Such programmers may even use an editor or an IDE, which automatically creates getters and setters for all private attributes. These tools even warn the programmer if she or he uses a public attribute! Java programmers will wrinkle their brows, screw up their noses, or even scream with horror when they read the following: The Pythonic way to introduce attributes is to make them public.
We will explain this later. First, we demonstrate in the following example, how we can design a class in a Javaesque way with getters and setters to encapsulate the private attribute self.__x:
class P:
def __init__(self, x):
self.__x = x
def get_x(self):
return self.__x
def set_x(self, x):
self.__x = x
We can see in the following demo session how to work with this class and the methods:
from mutators import P
p1 = P(42)
p2 = P(4711)
p1.get_x()
Output:
42
p1.set_x(47)
p1.set_x(p1.get_x()+p2.get_x())
p1.get_x()
Output:
4758
Getter And Setter in Python فى لغة بايثون
Теги
كورس بايثونبايثونتعليم لغة بايثونPythonPython CoursesAll Python courses.دورة تعلم بايثون من الصفر كاملة للمبتدئين - Master Python from Beginner to Advanced in Arabic.تعلم لغة. Python درس 001 - مقدمة عن الدورة وما هي لغة Python..Mastering Python..تعلم لغة بايثون من الصفر الى الاحتراف | كورس كامل..Python Tutorial. - Python for Beginners [Full Course.البرمجة الكائنية فى لغة بايثونOOP in pythonGetter And Setter in Python فى لغة بايثون