0

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
Mighty God Loki
  • 135
  • 3
  • 10
  • 1
    There is no private in Python: https://stackoverflow.com/a/2064212/9741277 (it is really just a naming convention) – leun4m Mar 02 '23 at 09:47
  • 1
    See [Inheritance of private and protected methods in Python](https://stackoverflow.com/questions/20261517/inheritance-of-private-and-protected-methods-in-python) – InsertCheesyLine Mar 02 '23 at 09:49
  • Privates of _other objects of the same class_ can explicitly be accessed. It's not confined to just `self`. Classes know their internal structure and are trusted to modify objects of their class, be it `self` or another instance. – deceze Mar 02 '23 at 09:54
  • I know the duplicate is about PHP, but the answer is a language neutral explanation of the concept. – deceze Mar 02 '23 at 09:57

0 Answers0