I created a piece of code and I am curious to know why am I able to execute a private method of a class. The Code is below.
I know that in Python private methods are not really "private" since I can call a private method of class from anywhere in program by name mangling i.e object._classname__method()
But from my understanding I should not be able to call (but I can!) the private method "__change_self_name()" of any other object outside its own class right? What am I understanding incorrectly here?
class Parent:
def __init__(self, name):
self.name = name
def __private_method_parent(self):
print("This is a private method from Parent")
def change_others_name(self, other_object):
# How can I execute private method of other object?
other_object.__change_self_name()
def __change_self_name(self):
self.name = 'New Name'
class Child_1(Parent):
def __init__(self, name):
super().__init__(name)
class Child_2(Parent):
def __init__(self, name):
super().__init__(name)
a_child = Child_1('Name1')
b_child = Child_2('Name2')
print(b_child.name)
# Output : Name2
a_child.change_others_name(b_child)
print(b_child.name)
# Output : New Name
print(a_child.__private_method_parent())
# Output : Error