[Tutor] Advantage of subclassing UserDict and UserList

Andrei Kulakov ak@silmarill.org
Thu, 29 Nov 2001 03:21:38 -0500


On Thu, Nov 29, 2001 at 01:23:12PM +0530, karthik Guru wrote:
> hi all,
> 
> What are the advantages of subclassing UserDict and UserList classes??
> 
> import UserList
> 
> class myclass(UserList.UserList):
> 
>     def __init__(self):
>             UserList.UserList.__init__(self)
>     def append(self,item):
>             import types
>             if type(item) == types.IntType:
>                     UserList.UserList.append(self,item)
>             else:
>                     raise "Sorry only ints!"
> 
> 
> ok here i have restricted the user from entering any other type other than
> "ints"
> by overriding append().
> 
> Is there any other advantsge of subclassing these classes other than
> imposing such restrictions?.
> 
> thanks in advance,
> karthik.

Yes, you can for example make ordered dict:

class SortedDict(UserDict.UserDict):
    """Sorted dictionary for dict of directories"""
    def keys(self):
        l = self.data.keys()
        l.sort()
        return l
    def items(self):
        l = self.data.items()
        l.sort()
        return l

> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org