1. Single Underline:
A single underline named variables (including classes, functions, generic variables) cannot be imported into another module through the From module import *.
testa.py
# testa.py
_foo (object):
Fun (self):
print (' Fun in Class _foo ')
_bar (a):
Print (a)
testb.py
*
a = _foo ()
_bar (' Hello World ')
C = _foobar
Testb.py will complain:
Traceback (most recent call last):
<module>
a = _foo ()
defined
2. Double underline:
There are no private keywords in python to control the variables of class member access, but you can achieve the same effect by naming the variable as a double underline, in the form of __xxx (not __xxx__, which has a special meaning and is accessible).
>>> class Foo (object):
def __init__ (Self, a):
self.__a = a
def __fun (self):
print (self.__a)
>>> t = Foo (MB)
>>> t.__fun ()
Traceback (most recent call last):
File "<pyshell# 25> ", line 1, in <module>
t.__fun ()
attributeerror: ' Foo ' object has no attribute ' __fun '
>> > T.__a
traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
t.__a< C14/>attributeerror: ' Foo ' object has no attribute ' __a '
>>>
The class itself can access the __XXX variable, but not in other scopes. The principle is that in Python the variable variable in the __xxx form of the class is restructured to _classname__xxx, so the variable in the __xxx form cannot be accessed.
In fact, it can be accessed through _classname__xxx, but not recommended, the code is as follows:
>>> class Foo (object):
def __init__ (Self, a):
self.__a = a
def __fun (self):
print (self.__a)
>>> t = Foo (MB)
>>> t._foo__a
100
3. __slots__: __slots__ can control the increase of class member variables, only variables appearing in __slots__ can be added to the class.
>>> class Foo ():
__slots__ = (' name ', ' age ')
def __init__ (self, A, b):
self.name = a
self.age = 1 9
self.addr = ' i '
>>> t = Foo (' Xmr ', a)
Traceback (most recent call last):
File "<pyshel L#68> ", line 1, in <module>
t = Foo (' xmr ', @)
File" <pyshell#67> ", line 6, in __init__
SELF.A DDR = 1000
attributeerror: ' Foo ' object has no attribute ' addr '
>>>
>>> class Bar (): c14/>__slots__ = (' name ', ' age ')
def __init__ (self, A, b):
self.name = a
self.age =
>>> t = Bar (' xmr ',%)
>>> t.name = ' xmr '
>>> t.age = '
>>> t.addr = ' ' '
Aceback (most recent):
File "<pyshell#76>", line 1, in <module>
t.addr = ' the '
Ributeerror: ' Bar ' object has no attribute ' addr '
>>>
Neither class Foo nor bar in the above code can increase other member variables except name and age, because only name age is in the __slots__.
4. @property:
The role of @property is to use a member function as a variable, but the variable cannot be modified:
>>> a = Foo (MB)
>>> a.fun
>>> a.fun =
Traceback (most recent call Las T):
File "<pyshell#97>", line 1, in <module>
a.fun =
attributeerror:can ' t set attribute
5.__all__:
Continue to do not finish ...