Skip to content Skip to sidebar Skip to footer

Actual Implementation Of Private Variables In Python Class

Possible Duplicate: The meaning of a single- and a double-underscore before an object name in Python I had a question when I was reading the python documentation on private vari

Solution 1:

  • Guido van Rossum put it: we are all adults.
  • The extended version: We are all adults. Feel free to shoot yourself in the foot if you must.

You can hide it a bit if you must, but you really shoudn't:

class NonAdult(object):
    def __init__(self):
        self.__private_number = '42'
    def __getattr__(self, name):
        if name.startswith('__private'):
            raise AttributeError

if __name__ == '__main__':
    na = NonAdult()
    print(na.__private_number) # raises AttributeError
    print(na.__dict__['_NonAdult__private_number']) # would still return 42

Solution 2:

No, there are no private variables or methods in Python objects. The phrase "We're all consenting adults here" is generally used to explain that they are seen as unnecessary.

A single underscore is sometimes used for "private" members, buy only as a convention; it serves no functional purpose.

Leading double underscores cause name mangling, but are only intended to avoid naming collisions in subclasses. It does not provide any "private member safety", as you can still get to them.


Solution 3:

You can use a double leading underscore to invoke Pythons name mangling. So __priv becomes _MyClass__priv. It will still be accessible, but prevents subclasses from accidental overriding.


Post a Comment for "Actual Implementation Of Private Variables In Python Class"