1

Hello there i am very new to python (and i am from java background ) my question is does the predefined functions such as length, size or init (constructor of a class) starts with

__function__()

is this standard python syntax that every predefined should starts with this symbol ? ( for example touple.__len__() )? if not then whats the purpose of use this symbol i am asking this quesion because this symbol confuse me a lot in python.

NaN
  • 683
  • 1
  • 8
  • 15
  • Take a look here, http://docs.python.org/2/reference/datamodel.html –  Nov 23 '13 at 15:56
  • http://www.python.org/dev/peps/pep-0008/#naming-conventions – zero323 Nov 23 '13 at 15:57
  • This is documented in http://docs.python.org/2/reference/lexical_analysis.html#reserved-classes-of-identifiers and http://docs.python.org/2/reference/datamodel.html#special-method-names – Martijn Pieters Nov 23 '13 at 16:08

3 Answers3

3

In python, method names which start and end in a double underscore have special meaning and are, by convention, reserved (there is nothing preventing you from creating your own "special" names, but you should rather not). For example, they are used to implement operator overloading.

You can find a nice introduction in A Guide to Python's Magic Methods. You can also see the Data model - Special method names section of the language reference.

You should also note that methods with an initial double underscore and no final double underscore are treated specially by the interpreter (they are name-mangled so that you get a "private-ish" method). This has nothing to do with methods starting and ending with a double underscore.

tawmas
  • 7,443
  • 3
  • 25
  • 24
1

Something that begins and ends with a double underscore or often called a dunder, is a magic function or method. Usually, they make objects work with operators or base functions (like len or statements like del, so basically functions or statements of importance).

So, for example:

  1. __add__ is for the + operator
  2. __mul__ is for * operator.

So, if you have two objects of the same type say Foo, then Foo('a') + Foo('b'), would call Foo('a').__add__(Foo('b')).

They behave as reserved words and have some protection. So, for example:

class Foo(object):

    def __init__(self):
        self.x = 10

    def __len__(self):
        return "Cheese"


if __name__ == '__main__':
    a = Foo()
    print a.__len__()

would print out Cheese to the console. However, this would give you a TypeError:

if __name__ == '__main__':
    a = Foo()
    print len(a)
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
-2

the __ and _ symbol is for "private" functions

usually you do not use function name with _. functions that start with _ are usually python's and are being used so dont override them or something if you dont know what you are doing

if you want to make a function "private" you use _. e.g : def _myFunc()

user2953680
  • 564
  • 1
  • 5
  • 16