python - What is the meaning of a single- and a double-underscore before an object name? -


i want clear once , all. can please explain exact meaning of having leading underscores before object's name in python? explain difference between single , double leading underscore. also, meaning stay same whether object in question variable, function, method, etc?

single underscore

names, in class, leading underscore indicate other programmers attribute or method intended private. however, nothing special done name itself.

to quote pep-8:

_single_leading_underscore: weak "internal use" indicator. e.g. from m import * not import objects name starts underscore.

double underscore (name mangling)

from the python docs:

any identifier of form __spam (at least 2 leading underscores, @ 1 trailing underscore) textually replaced _classname__spam, classname current class name leading underscore(s) stripped. mangling done without regard syntactic position of identifier, can used define class-private instance , class variables, methods, variables stored in globals, , variables stored in instances. private class on instances of other classes.

and warning same page:

name mangling intended give classes easy way define “private” instance variables , methods, without having worry instance variables defined derived classes, or mucking instance variables code outside class. note mangling rules designed avoid accidents; still possible determined soul access or modify variable considered private.

example

>>> class myclass(): ...     def __init__(self): ...             self.__superprivate = "hello" ...             self._semiprivate = ", world!" ... >>> mc = myclass() >>> print mc.__superprivate traceback (most recent call last):   file "<stdin>", line 1, in <module> attributeerror: myclass instance has no attribute '__superprivate' >>> print mc._semiprivate , world! >>> print mc.__dict__ {'_myclass__superprivate': 'hello', '_semiprivate': ', world!'} 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -