Python private variable questions

Asked 2 years ago, Updated 2 years ago, 14 views

class num():
    def __init__(self, v):
        self.__k = v

    def getK(self):
        return self.__k

    def setK(self, v):
        self.__k = v


n = num(10)
 # print(n.__k) inaccessible (error)
print(n.getK())

n.setK(20) #Good
print(n.getK())

n.__k = 30 # Why does this code work?
           # If you have this code, you can also print below. If you don't have it, it's
print(n.__k)

If you run it, you'll get a very good output of 102030.

I learned that if you use two underscore __ before a variable in an instance, it becomes private that cannot be accessed from the outside. But why does n.__k = 30 work? And why does the print on the bottom line work?

python

2022-09-20 20:02

1 Answers

Let's be clear

Python is not private.

__ Dunder notation does simple name mangling.

In the code below, a is renamed to ```_Aa`'.

Python is that kind of language.Programming linguistically, it seems to have a lot of problems, but that's why it's easy to write.

>>> class A:
...     ...     __a = 1
...     
>>> 
>>> dir(A)
['_A__a',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__']
>>> a = A()
>>> a._A__a
1
>>> a.__a
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'A' object has no attribute '__a'


2022-09-20 20:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.