-1

Below is a piece of code. I expect in the first print statement to print 456 but it is printing 123. Can anyone help with the explanation of this?

Have a look at the code below.

class employee():

    __private_var = 123
    phone_number=3274687

    def __init__(self, phone):
        self.phone_number = phone

# Private Functions

    def get_private_func(self):
        return self.__private_var

    def set_private_func(self):
        self.__private_var = 1

class VIP(employee):

    phone_number=123456
    __private_var = 456


obj1 = employee(1312321)
obj2 = VIP(1312321)
#Unable to reassign new value to private variable
print (obj2.get_private_func())

#Able to reassign new value to private variable
obj2.set_private_func()
print (obj2.get_private_func())

print (obj1.get_private_func())

Expected results:

456
1
123

Got these results:

123
1
123
chowmean
  • 152
  • 1
  • 9
  • 3
    Please simply the example. You don't need all these methods and abstractions. This whole question boils down to behavior of class attributes (namely those that start with `__`) in subclasses – DeepSpace Jul 09 '19 at 08:18
  • 3
    [Python name mangling](https://stackoverflow.com/a/34903236/6699447) – Abdul Niyas P M Jul 09 '19 at 08:25

2 Answers2

0

Class variable __private_var should be initialised as super(employee).__private_var not __private_var in VIP class.

Another approach:

class VIP(employee):
    __private_var = 456

    def get_private_func(self):
        return self.__private_var
Kshitij Saxena
  • 930
  • 8
  • 19
  • 1
    But why a VIP instance `get_private_func` did not access `__private_vaar` set on `VIP` class? – Lucas Wieloch Jul 09 '19 at 08:28
  • OK, but why is it not assigning the new value which is 456 in this case. Some explanation would be very helpful – chowmean Jul 09 '19 at 08:31
  • Python cannot figure out if you are assigning a value to the variable in the super class or creating a new variable in child class. The default behaviour is to create a new variable. – Kshitij Saxena Jul 09 '19 at 08:37
0

It's a behavior of private vars(namely the ones with a name that starts with __), make it not private and it should work(works on my machine)

Eden K
  • 79
  • 6