Polymorphism in Python

前端 未结 2 1498
旧时难觅i
旧时难觅i 2021-01-20 20:28
class File(object):
    def __init__(self, filename):
        if os.path.isfile(filename):
            self.filename = filename
            self.file = open(filename         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-20 21:15

    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.

提交回复
热议问题