changing a list within a subclass of list ?

Jan Samohyl samohyl at webseek.cz
Thu Oct 10 17:14:18 EDT 2002


Hello, I don't understand one aspect of builtin-types subclassing. Assume I have subclassed a list:

	class Mylist(list):
		pass

and would like to do something like:

	l=Mylist([1,2,3])

instead of 

	l=[1,2,3] 

for a standard list. What should I put in the constructor? I know I could do

	def __init__(self,newlist):
		list.__init__(self)
		self.extend(newlist)

but this has two problems:

(1) What if I need to modify the underlying list from within the class, eg. reassign it completely, what can I do then? 
Deleting and extending it seems quite ugly.

(2) It's not a general method, works for lists only, for dictionary there is a different way, and when (hopefuly some day) 
subclassing of immutable types becomes available, how will it be then done?

I mean, shouldn't there be some special method of list/dictionary/whatever, that would allow it to rebuild in-place somehow?

Best regards,
Jan Samohyl





More information about the Python-list mailing list