What do you use as symbols for Python ?

Peter Otten __peter__ at web.de
Sat Nov 12 08:27:18 CET 2005


Daniel Evers wrote:

> I mixed this with the class-version and created a new class derived from
> "str" for easier printing and added an iterator:
> 
> ---
> 
> class Enum:
>         class Type(str):
>                 def __init__(self, name):
>                         self.__name = name
>                 def __str__(self):
>                         return self.__name
> 
>         def __init__(self, *keys):
>                 self.__keys = []
>                 for key in keys:
>                         mytype = self.Type(key)
>                         self.__dict__[key] = mytype
>                         self.__keys.append(mytype)

You should ditch what follows and instead add just

          def __iter__(self):
              return  iter(self.__keys)

>                 self.__index = -1
>                 self.__count = len(keys)
> 
>         def __iter__(self):
>                 return self
> 
>         def next(self):
>                 self.__index = self.__index + 1
>                 if (self.__index >= self.__count):
>                         self.__index = -1
>                         raise StopIteration
>                 return self.__keys[self.__index]
> 
> friends = Enum("Eric", "Kyle", "Stan", "Kenny")
> print "These are my friends:",
> print ", ".join([kid for kid in friends])
> for kid in friends:
>         print kid,
>         if kid is friends.Kenny:
>                 print "dead"
>         else:
>                 print "alive"
> ---

To see the problem with your original code (an object serving as its own
iterator) try the following example:

    friends = Enum("Eric", "Kyle", "Stan", "Kenny")
    if "Kyle" in friends:
        print "Hi Kyle"
    print "My friends:", ", ".join(friends) 

Only Stan and Kenny show up in the last print statement because the
containment test did not iterate over all friends.

Also, Type.__name seems redundant. Just

class Type(str): pass

should do the job.

Peter










More information about the Python-list mailing list