polymorphism

Jeff Epler jepler at unpythonic.net
Mon May 12 22:06:41 EDT 2003


class Base:
    def f(self):
        print "f in base", self

    # "pure virtual function g"
    # no need to write anything

class Derived(Base):
    def f(self):
        print "f in derived", self
        # call overridden method--see also "super" in recent Python versions
        Base.f(self)

    def g(self):
        print "g in derived", self

# Calls the "f" method defined on whatever "o" is
def h(o):
    o.f()

>>> b = Base()
>>> d = Derived()
>>> 
>>> h(b)
f in base <__main__.Base instance at 0x81792bc>
>>> h(d)
f in derived <__main__.Derived instance at 0x8159d84>
f in base <__main__.Derived instance at 0x8159d84>
>>> d.g()
g in derived <__main__.Derived instance at 0x8159d84>
>>> b.g()
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
AttributeError: Base instance has no attribute 'g'





More information about the Python-list mailing list