Say in front of the point:
Python clearly has a private way of defining the method is to add a double glide line in front of the variable or method, which is actually a python pseudo-private. It's just a programmer's agreement that the rules are called private variables, but you can call them if you want to call them externally.
Python does not have true privatisation support, but can be used to get pseudo-private
(1) The member variable _xxx "single underline" is called a protection variable, which means that only class objects (that is, class instances) and subclass objects can access these variables themselves, which need to be accessed through the interface provided by the class; cannot be imported with ' from module import * '
(2) The private variable/method name in the __xxx class (a Python function is also an object, so a member method called a member variable can also work.) , the "double underscore" begins with a private member, meaning that only the class object can access it, and even the subclass object cannot access the data.
(3) __xxx__ System definition name, there is a "double underline" for the special method in Python, such as __init__ () represents the constructor of the class.
classB:def __init__(self): self.__private=0 Self._private=1def __private_method(self):Pass defPublic_method (self):PassSelf .__private_method() b=B ()#print (b.__private) #双下划线, no access to dataPrint(b._private)#single underline, you can access the
It is also important to note that private attributes cannot be accessed, such as
classB:def __init__(self): self.__private1= 100Self._private2=99def __private_method(self):Pass defPublic_method (self):PassSelf .__private_method() b=B ()#print (b.__private1) #双下划线, no access to dataPrint(B._PRIVATE2)#single underline, you can access thePrint(b._b__private1
Private variable: instance. _ Class name __ variable name
Private method: Instance. _ Class Name __ Method name ()
So this is a pseudo-private, but a programmer agreed to commonly known as the rules.
There are two different coding conventions (single underline and double underscore) to name private properties, so the question is: Which Way is good? For the most part, you should let your non-public name begin with a single underscore. However, if you know that the code will involve subclasses, and some internal attributes should be hidden in the subclass, then consider using a double-underline scheme.
Python base = = = Private property of Class (pseudo-Private)