OO in Python? ^^

Tony Nelson *firstname*nlsnews at georgea*lastname*.com
Sat Dec 10 18:43:19 EST 2005


In article <dnfmcm$aqp$02$1 at news.t-online.com>,
 Matthias Kaeppler <void at void.com> wrote:
 ...
> obj = Base() # I want a base class reference which is polymorphic

obj now refers to an instance of Base.

> if (<need D1>):
>     obj =  D1()

obj now refers to an instance of D1().  The Base instance is 
unreferenced.

> else:
>     obj = D2()

obj now refers to an instance of D2().  The Base instance is 
unreferenced.

Note that there is no code path that results in obj still referring to 
an instance of Base.  Unless making a Base had side effects, there is no 
use in the first line.


> I could as well leave the whole inheritance stuff out and the program 
> would still work (?).

That program might.


> Please give me hope that Python is still worth learning :-/

Python has inheritance and polymorphism, implemented via dictionaries.  
Python's various types of namespace are implemented with dictionaries.

Type this in to the Python interpreter:

class Base:
    def foo(self):
        print 'in Base.foo'

class D1(Base):
    def foo(self):
        print 'in D1.foo'
        Base.foo(self)

class D2(Base):
    def foo(self):
        print 'in D2.foo'
        Base.foo(self)

def makeObj():
    return needD1 and D1() or D2()

needD1 = True
makeObj().foo()

needD1 = False
makeObj().foo()
________________________________________________________________________
TonyN.:'                        *firstname*nlsnews at georgea*lastname*.com
      '                                  <http://www.georgeanelson.com/>



More information about the Python-list mailing list