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 is: what happened? How can I fix my code to use FileA FileA.__read()to read a file instead File.__read()?: S

Thanks in advance.

+3
source share
2 answers

The double underscore attribute prefix does not make the attribute private; it simply makes polymorphism impossible, because the attribute name is distorted with the current class name. Instead, change it to one underscore prefix.

+7
source

You can also leave the undefined method 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')

To understand Python classes, it is invaluable to have such an understanding of class inheritance.

+1

Source: https://habr.com/ru/post/1770223/


All Articles