One, double underline
If you want the internal properties to be inaccessible externally, you can add two underscores to the name of the property, and __
in Python, the variable name of the instance __
becomes a private variable (private), which can only be accessed internally and cannot be accessed externally.
is an instance variable that starts with a double underscore not necessarily externally accessible? Actually, it's not. cannot be accessed directly __name
because the Python interpreter has changed the variable to the outside __name
, so it is _Student__name
still possible _Student__name
to access the __name
variable.
The external code can set the __name
variable, but actually the variable __name
and the variable inside the class are __name
not a variable! The internal __name
variables have been automatically changed by the Python interpreter _Student__name
, and the external code has added a variable to the instance __name
.
1>>>classStudent (object):2...def __init__(self, name):3.. self.__name=name4...defget_name (self):5...returnSelf.__name6...defset_name (self, name):7.. self.__name=name8 ... 9>>> st = Student ('Jack')Ten>>>St.get_name () One 'Jack' A>>> St.set_name ('Mike') ->>>St.get_name () - 'Mike' the>>>dir (ST) -['_student__name','__class__','__delattr__','__dict__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__le__','__lt__','__module__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','__weakref__','get_name','Set_name'] ->>> St.__name - Traceback (most recent): +File"<stdin>", Line 1,inch<module> -Attributeerror:'Student'object has no attribute'__name' +>>>St._student__name A 'Mike' at>>> St.__name='New' #added a new variable to the instance ->>> St.__name - 'New' ->>>St._student__name - 'Mike'
Two, single underline
There are times when you see an instance variable name that starts with an underscore, such as an _name
instance variable that can be accessed externally, but, as you see in the rules, when you look at a variable like this, the meaning is, "although I can be accessed, please treat me as a private variable and don't feel free to access it."
1 >>> class Student (object): 2 ... def __init__ (self, name): 3 ... self._name = name 4 ... 5 >>> st = Student ( " jack " ) 6 >>> st._name 7 " jack "
Third, special variables
A variable that starts with a double underscore and ends with a double underscore, and the special variable is directly accessible, not a private variable.
1>>>classStudent (object):2...def __init__(self, name):3.. self.__name=name4...defget_name (self):5...returnSelf.__name6 ... 7>>> st = Student ('Jack')8>>>St.get_name ()9 'Jack'Ten>>> St.__init__('Mike') One>>>St.get_name () A 'Mike'
Python object-oriented three access rights underline double underscore