[Python-de] Unterklassen von eingebauten Typen definieren
Gerhard Häring
haering_python at gmx.de
Sun Sep 29 20:27:35 EDT 2002
* Gregor Lingl <glingl at aon.at> [2002-09-29 18:50 +0200]:
> Hallo pythonistas!
>
> Ich möchte gerne folgendes wissen:
>
> Ich leite eine Klasse in folgender Weise vom eingebauten Typ list ab:
Die Dokumentation dafür sehr spärlich ist: </yoda>
http://www.python.org/2.2.1/descrintro.html
> >>> class L(list):
> pass
>
> >>> a = L()
> >>> a
> []
> >>> b = L([1,2,3])
> >>> b
> [1, 2, 3]
> >>> c = L("xyz")
> >>> c
> ['x', 'y', 'z']
> >>>
>
> L scheint list als Konstruktor zu benützen, oder
> es verhält sich wenigstens so als ob.
>
> Nächstes Beispiel:
>
> >>> class M(list):
> def __init__(self, x):
> self.x = x
Du hast vergessen, dass du noch den Konstruktor der Oberklasse aufrufen
musst: list.__init__(self, x)
Hier ein kleines Beispiel:
class M(list):
def __init__(self, initparm, doUpperCase=0):
if doUpperCase:
initparm = [x.upper() for x in initparm]
list.__init__(self, initparm)
m = M(("a", "A", "b"), 1)
print m
-- Gerhard
More information about the Python-de
mailing list