Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python leading underscore _variables

Tags:

python

We know that in a class, functions starting with __function__ do not get imported while using:

from module import *

Someone asked what is an _variable? I have never used one.
Do they exist? Is this a concept of variable which cannot be accessed using class object or something?

like image 830
Arindam Roychowdhury Avatar asked Apr 03 '12 17:04

Arindam Roychowdhury


People also ask

What does _ and __ mean in Python?

Enforced by the Python interpreter. Double Leading and Trailing Underscore( __var__ ): Indicates special methods defined by the Python language. Avoid this naming scheme for your own attributes. Single Underscore( _ ): Sometimes used as a name for temporary or insignificant variables (“don't care”).

Why do we use __ in Python?

The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.

What do 2 underscores mean in Python?

Double underscores are used for fully private variables. According to Python documentation − If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores.

Can you start a Python variable name with an underscore?

Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


2 Answers

It is a naming convention for private variables. See 9.6, private variables: http://docs.python.org/tutorial/classes.html#private-variables

like image 182
Thomas Dignan Avatar answered Oct 16 '22 20:10

Thomas Dignan


A variable name starting with an underscore is a strong hint that this variable should be viewed as private.

Read http://docs.python.org/tutorial/classes.html#private-variables

like image 32
Matthias Avatar answered Oct 16 '22 20:10

Matthias