In python, we often see a lot of variable names begin with an underscore _ and the number underlined not the same, then the effect of these variables in the end is what?
Variable name Category:
# The number that begins with the letters: normal public variable name
A =. 1
DEF AA ():
Pass
# begin single underline: semi-private variable name
_B = 2
DEF _bb ():
Pass
# begin double-underlined: private variable name
= 3 __C
DEF __cc ():
Pass
# starts with a double underline, double underline ending: the built-in property name or method name magic
__name__, __dir__
Public variable name:
With such names named object, the object is public, anyone can use
Semi-private variable names:
With such names named objects need to be divided into two cases
1. outside the class
Objects outside the semi-private class, private object, functions the same, are present in the normal use of the module, but can not be directly imported and called
If you must use outside the module, you need to import this module, then use (module name variable name) call
2. class
The semi-private class objects, just the concept of private, default not to make calls outside the class
The actual outside the class, can be used (name instance variable name / class name variable name) Called
Private variable name:
With such names named object, also we need to be divided into two cases
1. outside the class
Objects in this case, semi-private and objects, can refer to the above
2. class
Class private object, outside the class can not be called directly, can be interpreted as true private
However, python is not completely private objects, such objects also can be called outside the class, a concept involved here: straightening
class A:
def get_1(self):
return 1
def _get_2(self):
return 2
def __get_3(self):
return 3
print(dir(A))
结果为:
['_A__get_3', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', '_get_2', 'get_1']
From the printed result, we see that there is no class A __get_3 such a property, but there is a _A__get_3 property, which is straightening
python that appear in the class attributes of private or proprietary methods, straightening, straightening method is to add (_ class name) before the private property name, method name Private
So, when we want private property and method calls the class, you can call directly attribute name after straightening
Magic Methods:
This is a python own properties and methods to achieve, generally does not allow custom properties or methods similar naming of this
About the role of these methods and properties, you can try it yourself
Original: https://blog.csdn.net/baidu_28289725/article/details/81870462