Skip to content Skip to sidebar Skip to footer

Functions And Variables Beginning With A Single Or Double Underscore

I have seen functions and variables beginning with underscores in various programming languages(PHP and Python) and am confused about the meaning behind it.

Solution 1:

Assuming normal conventions are used in PHP:

  • single underscore indicates a protected member variable or method
  • double underscore indicates a private member variable or method

This stems from when PHP had weak OOP support and did not have a concept of private and protected (everything was public). This convention allowed developers to indicate a member variable or method was private or protected as to better communicate this to users of the code.

Users could choose to ignore these semantics and call the "private" and "protected" member variables and methods if so chose, though.

Solution 2:

single underscore has no special meaning for class/instance attributes in Python. By convention it indicates private variables/function. from module import * will not import functions and variables beginning with a single underscore. (thanks Bi Rico).

double underscore invokes name mangling. This lets classes have an attribute that is distinct from one with the same name in their subclasses.

Post a Comment for "Functions And Variables Beginning With A Single Or Double Underscore"