Custom Search

Friday, April 2, 2010

The Private Controversy in python

The Private Controversy in python

For private methods and functions, a leading underscore is conventionally added.
This rule was quite controversial because of the name mangling feature in Python.
When a method has two leading underscores, it is renamed on the fly by the
interpreter to prevent a name collision with a method from any subclass.
So some people tend to use a double leading underscore for their private attributes
to avoid name collision in the subclasses:

So some people tend to use a double leading underscore for their private attributes
to avoid name collision in the subclasses:

>>> class Base(object):
... def __secret(self):
... print "don't tell"
... def public(self):
... self.__secret()

>>> Base.__secret

Traceback (most recent call last):
File "", line 1, in
AttributeError: type object 'Base' has no attribute '__secret'

>>> dir(Base)
['_Base__secret', ..., 'public']

>>> class Derived(Base):
... def __secret(self):
... print "never ever"

>>> Derived().public()
don't tell

--------------------------------------------

No comments:

Post a Comment