0

I am trying to understand the difference between the class attributes __value and value in below python class.

class WithClass ():
    def __init__(self, val = "Bob"):
        self.__value = val
    def my_func(self):
        print(self.value)
a = WithClass()
print(a.__value)
b = WithClass("Sally")
print(b.__value))

Above code gives error "AttributeError: WithClass instance has no attribute '__value'". But below code does not give any error.

class WithClass ():
    def __init__(self, val = "Bob"):
        self.value = val
    def my_func(self):
        print(self.value)
a = WithClass()
print(a.value)
b = WithClass("Sally")
print(b.value))

What is the difference between the declaration of two attributes? Any resources to understanding the importance of "__" in python would be appreciated.

pooja kosala
  • 29
  • 3
  • 8
  • 1
    Possible duplicate of [What is the meaning of a single and a double underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name) – kyle Nov 02 '18 at 02:38

1 Answers1

0

Adding two underscores in front of a class variable performs "name mangling", effectively making the variable private to the outside world (so it is not as easy for code outside the class to change it). More information about it is viewable in the python documentation.

infobiac
  • 163
  • 9