Python variable or function name
An identifier in python can contain numbers, letters, and underscores (_), but must start with a letter or underscore (_). The name starting with underscore (_) has special meanings.
Names with double underscores (_)
It is generally used for naming special methods to implement some behaviors or functions of objects. For example, the _ new _ () method is used to create an instance, and the __init _ () method is used to initialize objects,
The x + y operation is mapped to method x. _ add _ (y), sequence or dictionary index operations x [k] ing to x. _ getitem _ (k) ,__ len _ () and _ str _ () are called by built-in functions len () and str () respectively.
Only names with double underscores (_)
Used for Object Data encapsulation. The attributes or methods named in this form are private attributes or private methods of the class.
class Foo(object): def __init__(self): self.__name = 'private name' def getname(self): return self.__name def __spam(self): print 'private method' def bar(self): self.__spam()
If you directly access private properties or methods externally:
>>> f = Foo()>>> f.__nameTraceback (most recent call last): File "<pyshell#1>", line 1, in <module> f.__nameAttributeError: 'Foo' object has no attribute '__name'>>> f.__spam()Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> f.__spam()AttributeError: 'Foo' object has no attribute '__spam'
It is not feasible, which plays a role in hiding data. However, this implementation mechanism is not very strict and is implemented through automatic "deformation, all _ names starting with double underscores in the class are automatically changed to a new name of "_ class name_name:
>>> f._Foo__name'private name'>>> f._Foo__spam()private method
In this way, you can access it.
This mechanism can prevent the inheritance class from being redefined or changing the implementation of the method, for example, defining a Foo derived class:
class Goo(Foo): def __spam(self): print 'private method of Goo'
Override the _ spam method and run:
>>> g = Goo()>>> g.bar()private method
When calling the bar () method, the _ spam () method of the Foo class is still executed, because in the implementation of the bar () method, self. _ spam () is automatically deformed to self. the same applies to the bar () method inherited by _ Foo _ spam () and Goo.
Name starting with an underscore _
It is generally used for the name defined by "private" in the module.
The from module import * statement is used to load all the names in the module. To control the import name, define the LIST _ all __, only the names in _ all _ can be imported through,
Another method is to name a definition starting with a single underline. This definition will not be imported.
Of course, you can also name attributes or methods with a single underline in the class. This only indicates that the class definer wants these attributes or methods to be "private ", but it does not actually play any role.