[Tutor] subclass question

bob gailer bgailer at gmail.com
Mon Dec 21 16:43:59 CET 2009


David Perlman wrote:
> If I make a subclass of a built-in class, like this:
>
> class mylist(list):
>     def __init__(self):
>         list.__init__(self)
>
> Then it is valid for me to do this:
>
> >>> x=mylist()
> >>> x.hello=3
> >>>
>
> But I can't do this:
>
> >>> y=list()
> >>> y.hello=3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'list' object has no attribute 'hello'
> >>>
>
> What is it that is special about built-in classes that prevents you 
> from adding methods or, uh, whatever the generic term is for 
> sub-variables?  Is there a way to make your own classes restricted 
> like that? 
Classes, instances, functions may have user-defined attributes. Built-in 
data types such as list may not. Hence the need to subclass (e.g. list) 
to add additional attributes.

-- 
Bob Gailer
Chapel Hill NC
919-636-4239


More information about the Tutor mailing list