D
Duncan Booth
T. Kaufmann said:A simple but important question:
How can I initialize a super class (like dict) correctly in my
subclass constructor?
A sample:
class MyClass(dict):
def __init__(self):
dict.__init__(self)
...
Is there a general rule to do this for all buil-in types?
There are two rules. Generally, immutable objects get their initial values
from the constructor (__new__) while mutable objects are constructed with a
default value (e.g. empty list or dict) and are then set by the initialiser
(__init__) method. A few types which you might expect to be immutable are
actually mutable (e.g. property).
Mutable example (use for list, dict, property, etc.):
class MyClass(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
Immutable example (use for tuple, int, etc.):
class MyClass(tuple):
def __new__(cls, *args, **kw):
return tuple.__new__(cls, *args, **kw)
If there is any chance of your class being subclassed with multiple
inheritance involved, you should consider using super instead of naming the
baseclass directly, but most of the time you can get away with a direct
call to the baseclass.