How to implement C++ equivalent of templates

Alex Martelli aleaxit at yahoo.com
Sat Aug 18 02:59:01 EDT 2001


"Learn Python" <learnpython at hotmail.com> wrote in message
news:mailman.998113228.23710.python-list at python.org...
>
> Was trying to write my vector.
> Am not able to write a class which encloses a list and control access to
the
> list through __setitem__ and __getitem__ because
>
> isinstance() expects a class name as the argument and not a string
> representation of the class.

So don't do it.  Type testing is bad news, so don't test types.

> So am not able to verify the actual class name
> @ runtime in the __setitem__ method
>
> i thougt i c'd allow the user to configure the class instances
> he wants to hold in the MyVector class __init__.
>
> can someone show tell me how this can be done?

You can have __init__ take the class object if you're so keen on
using isinstance.  No need to pass strings -- a class is an object.
But, as usual with typetesting, you're not really giving much
added value, just overhead and headaches.

Anyway, if you insist:

class Homogeneous:
    def __init__(self, klass):
        self.klass = klass
        self.data = []
    def append(self, item):
        if not isinstance(item,self.klass):
            raise TypeError
        self.data.append(item)

and so on, to be called e.g.:

class Whatever: pass

h = Homogeneous(Whatever)
h.append(Whatever()) # works
h.append(23) # raises


Alex






More information about the Python-list mailing list