How to access dundle method from a subclass in Python?

99 Views Asked by At

I there a way to directly access dundle method in sub-class of Python ?

Imagine I have the following classes :

class Parent(object):
    def __init__(self, x):
        self.x = x
    
    def __add(self,y):
        return self.x + y
    
    def addition(self,y):
        return self.__add(y)

class Children(Parent):
    
    def add(self,y):
        return self.__add(y)

I can obviously instantiate the two classes, and use addition on both, but I can't use add from instance of Children. How could I access __add method inherited from Parent class to Children class ?

p = Parent(2)
p.addition(4)

c = Children(5)
c.addition(4)

all these calls work, but the two below don't

p.__add(5)  # AttributeError: 'Parent' object has no attribute '__add'
c.add(4)  # AttributeError: 'Children' object has no attribute '_Children__add'

And both return absence of attribute. The first behavior is the expected one, I do not want to change, but the second one is disturbing to me, since a sub-class should be able to access its parent hidden method, shouldn't it ?

More details : in fact the parent class in my case are dealing with a DB connection, and deal with username and passwords, with some method to check the password __check_password that I prefer to let 'private'. I'd like to call __check_password from different child classes, that deal with data manipulation later.

0

There are 0 best solutions below