Inheriting (subclass) of dict data attribute (copying)
Aaron S. Hawley
Aaron.Hawley at uvm.edu
Mon Jul 28 18:26:22 EDT 2003
On Sun, 27 Jul 2003, Aaron S. Hawley wrote:
> [What] Would be the most obvious (best in idiom) to overwrite the
> dictionary of my derived dict class? The old school way is obvious to
> me.
>
> TIA, /a
>
> #!/usr/bin/env python
>
> from UserDict import UserDict
>
> class Old_Chickens(UserDict): ## old school
> def __init__(self, chickens):
> self.set_chickens(chickens)
> def set_chickens(self, chickens):
> self.data = chickens
>
> class New_Chickens(dict): ## new school
> def __init__(self, chickens):
> self.set_chickens(chickens)
> def set_chickens(self, chickens):
> self = dict.__init__(self, chickens)
>
>
> new_chickens = New_Chickens({'white': 12, 'brown': 8})
> print new_chickens['white']
>
> old_chickens = Old_Chickens({'white': 12, 'brown': 8})
> print old_chickens['white']
this would probably be fine:
#!/usr/bin/env python
from UserDict import UserDict
class Old_Chickens(UserDict): ## old school
def __init__(self, chickens):
UserDict.__init__(self) #FIX: be sure to call the base __init__
self.set_chickens(chickens)
def set_chickens(self, chickens):
self.data = chickens
class New_Chickens(dict): ## new school
def __init__(self, chickens):
dict.__init__(self) #FIX: again, be sure to call the base __init__
self.set_chickens(chickens)
def set_chickens(self, chickens):
dict.__init__(self, chickens) #FIX: you need only recall __init__
...
try reading the "Unifying types and class in Python 2.2" before posting
a question about subclassing types:
http://www.python.org/2.2/descrintro.html
More information about the Python-list
mailing list