Polymorphism In Python
class File(object): def __init__(self, filename): if os.path.isfile(filename): self.filename = filename self.file = open(filename, 'rb')
Solution 1:
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.
Solution 2:
You can also leave the method undefined in the base class to achieve the same effect.
import os
classFile(object):
def__init__(self, filename):
if os.path.isfile(filename):
self.filename = filename
self.file = open(filename, 'rb')
self._read()
else:
raise Exception('...')
classFileA(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.
Post a Comment for "Polymorphism In Python"