Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to call parent class-private methods from child class in Python?

I’m trying to call __search from parent class A in child class B but I get the error:

AttributeError: 'B' object has no attribute '_B__search'

This seems to be only happening for methods starting with __. Is there a way to call these class-private methods when doing inheritance?

class A:
    def __init__(self, a):
        self.a = a
        
    def __search(self):        
        return self.a

    def display(self):
        print(self.a)

class B(A):
    def display(self):
        res = self.__search()
        return res

cB = B(2)

cB.display()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, but it’s terrible practice.

In Python, a method whose name begins with __ and does not end with it (so magic methods like __add__ are excluded) is obfuscated with the class name. That is,

class A:
  def __foo(self):
    return 1

is equivalent to

class A:
  def _A__foo(self):
    return 1

So if you really want to call __search defined on A, you should write

res = self._A__search()

Again, this is bad practice. Methods starting with __ are obfuscated because that’s the Python convention for private functions, so they shouldn’t be called from outside the class or in subclasses. You mention in the comments that this is a temporary fix, so that’s understandable, but I do hope it’s not intended to stay this way for very long.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading