subclassing Python types

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Thu Aug 30 15:18:06 EDT 2007


zzbbaadd at aol.com wrote:
> I have read that you can derive from the base classes such as str,
> list, dict.
> 
> I guess this would look like:
> 
> def MyString(str):
> def MyList(list):
> def MyDict(dict):
> 
> 
Well, replace 'def' with 'class' and you're right.

> How do you access the data that is contained in the super class?
> 
This way:
 >>> class MyList(list):
...    def do_something(self):
...       self.append(3)
...       print self
...
 >>> l = MyList((1, 2))
 >>> l
[1, 2]
 >>> l.do_something()
[1, 2, 3]


That is: Whenever you want to refer to the value refer to self (that is, 
refer to the instance of your class).

/W



More information about the Python-list mailing list