Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in Python

How can I make methods and data members private in Python? Or doesn't Python support private members?

like image 388
appusajeev Avatar asked Jan 14 '10 13:01

appusajeev


People also ask

How do you declare a private data member in Python?

Data members of a class are declared private by adding a double underscore '__' symbol before the data member of that class.

What is private attribute in Python?

In the context of class, private means the attributes are only available for the members of the class not for the outside of the class.

What is public and private data members in Python?

The variables which are defined inside the class is public by default. These variables can be accessed anywhere in the program using dot operator. A variable prefixed with double underscore becomes private in nature. These variables can be accessed only within the class.

How do you use private in Python?

In python programming, there are no private methods that cannot be accessed except inside the class. To define the private method, you have to prefix the member name with a double underscore(__).


1 Answers

9.6. Private Variables

“Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

So, for example,

class Test:     def __private_symbol(self):         pass     def normal_symbol(self):         pass  print dir(Test) 

will output:

['_Test__private_symbol',  '__doc__',  '__module__',  'normal_symbol'] 

__private_symbol should be considered a private method, but it would still be accessible through _Test__private_symbol.

like image 142
jbochi Avatar answered Sep 21 '22 08:09

jbochi