Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism in Python

class File(object):
    def __init__(self, filename):
        if os.path.isfile(filename):
            self.filename = filename
            self.file = open(filename, 'rb')
            self.__read()
        else:
            raise Exception('...')

    def __read(self):
        raise NotImplementedError('Abstract method')

class FileA(File):
    def __read(self):
        pass

file = FileA('myfile.a')

# NotImplementedError: Abstract method

My question: what's wrong? How I can fix my code to FileA use FileA.__read() to read the file instead of File.__read()? :S

Thank you in advance.

like image 869
Paulo Freitas Avatar asked Mar 09 '26 22:03

Paulo Freitas


2 Answers

Prefixing an attribute with double underscores doesn't make the attribute private, it simply makes polymorphism impossible because the attribute name gets mangled with the current class name. Change it to a single underscore prefix instead.

like image 187
Ignacio Vazquez-Abrams Avatar answered Mar 11 '26 12:03

Ignacio Vazquez-Abrams


You can also leave the method undefined in the base class to achieve the same effect.

import os
class File(object):
    def __init__(self, filename):
        if os.path.isfile(filename):
            self.filename = filename
            self.file = open(filename, 'rb')
            self._read()
        else:
            raise Exception('...')
class FileA(File):
    def _read(self):
        pass
file = FileA('myfile.a')

It is invaluable to the understanding of Python classes to have this understanding of class inheritance.

like image 28
freegnu Avatar answered Mar 11 '26 10:03

freegnu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!