0

in Python 2.7 one can created private members of a class by preceding them with '__'

     >>> class Test:
    def __f():
        print 'hi'


>>> ob=Test()
>>> ob.__f()

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    ob.__f()
AttributeError: Test instance has no attribute '__f'

In python one can define a function like f__(x) also. Then why isn't a function defined as

__f__(x)

not treated private?

>>> class Test2:
    def __f__(self):
        print 'hi'


>>> ob2=Test2()
>>> ob2.__f__()
hi

So how exactly are __f__() different from f()?

Anirudh Roy
  • 361
  • 1
  • 2
  • 10
  • Because name mangling does not apply for variables with more than one trailing underscore. – timgeb Mar 07 '17 at 16:07
  • What exactly are the special features of functions like __f__() when compared to just f() – Anirudh Roy Mar 07 '17 at 16:14
  • They're just special names for builtin functions by convention. The language has shortcuts for a lot of them. For example, you can use the bracket notation `a[0]` instead of writing `a.__getitem__(0)`. – timgeb Mar 07 '17 at 17:09

0 Answers0