KoZark
KoZark

Reputation: 85

Why private __var can change outside Class? (Python 3)

I have the following block:

class Bank:

    def __init__(self, b):
        self.__bal = b

def main():
    myaccount = Bank(2500)
    myaccount.__bal = 8000
    print(myaccount.__bal)

main()

and PyCharm prints: 8000. I want to ask how is it possible to change a private var __bal outside the class?

Upvotes: 2

Views: 305

Answers (2)

L3viathan
L3viathan

Reputation: 27333

You're not doing what you think you're doing.

Prefixing an attribute with double underscores performs "name mangling". You're just assigning a value to a new attribute. Observe:

class Bank:
    def __init__(self, b):
        self.__bal = b
    def show_bal(self):
        print(self.__bal)

And now, in interactive mode:

>>> b = Bank(23)
>>> b.__bal = 42
>>> b.show_bal()
23

Before you assign something to b.__bal you will also notice that accessing b.__bal doesn't work — because it doesn't exist yet. The actual value is still accessible, but its name is "hidden". Nothing prevents you from overriding "private" attributes (a concept that doesn't really exist in Python):

>>> b._Bank__bal = 99
>>> b.show_bal()
99

If you want to protect an attribute from change, the best way to do that is via properties, but even they will only protect the public interface of your class.

Upvotes: 2

Alok
Alok

Reputation: 9008

Let me tell you one thing about Python 3.

All members in a Python class are public by default. Any member can be accessed from outside the class environment.

Hence you can make changes to the variable. For more information about Python 3 class access modifiers, go here. Hope it clarifies your doubt.

Upvotes: 0

Related Questions