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
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
这是私有变量的行为(即名称以 __ 开头的变量),使其不是私有的,它应该可以工作(在我的机器上工作)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.