Question: Inheritance from a buil-in type

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • T. Kaufmann

    Question: Inheritance from a buil-in type

    Hi there,

    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__(s elf)
    ...


    Is there a general rule to do this for all buil-in types?

    Thanks for help.

    Thomas


  • Duncan Booth

    #2
    Re: Question: Inheritance from a buil-in type

    "T. Kaufmann" <merman@snafu.d e> wrote in news:3F7848C6.8 070306@snafu.de :
    [color=blue]
    > 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__(s elf)
    > ...
    >
    >
    > Is there a general rule to do this for all buil-in types?[/color]

    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__(s elf, *args, **kw)

    Immutable example (use for tuple, int, etc.):

    class MyClass(tuple):
    def __new__(cls, *args, **kw):
    return tuple.__new__(c ls, *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.

    --
    Duncan Booth duncan@rcp.co.u k
    int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
    "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

    Comment

    • Alex Martelli

      #3
      Re: Question: Inheritance from a buil-in type

      T. Kaufmann wrote:
      [color=blue]
      > Hi there,
      >
      > A simple but important question:
      >
      > How can I initialize a super class (like dict) correctly in my subclass
      > constructor?[/color]

      Generally, you also want to override __new__ -- not in all cases can
      you do all you want in __init__ by itself (e.g., it's far too late
      when you inherit from immutable types, such as numbers, str, tuple).

      [color=blue]
      > A sample:
      >
      > class MyClass(dict):
      > def __init__(self):
      > dict.__init__(s elf)
      > ...[/color]

      Yeah, you can do this, but the dict.__init__ call with just the
      self parameter is actually redundant (it wouldn't be if there
      WERE arguments -- either keyword ones, or a sequence of pairs,
      or both -- with which to actually initialize a non-empty dict...).

      [color=blue]
      > Is there a general rule to do this for all buil-in types?[/color]

      Generally, the super built-in may be advisable if you think you
      may ever be involved in a multiple-inheritance graph. But that
      is no different whether built-in types are involved, or not. I'm
      not sure what "general rule" may be different for built-in types
      than for others -- offhand, I don't think there are such differences.


      Alex

      Comment

      • Asun Friere

        #4
        Re: Question: Inheritance from a buil-in type

        Duncan Booth <duncan@NOSPAMr cp.co.uk> wrote in message news:<Xns9405A0 1F17467duncanrc pcouk@127.0.0.1 >...
        [color=blue]
        >
        > 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).
        >[/color]

        What is the thinking behind that? I mean you /can/ pass initial values
        to a mutable using __new__, eg

        class MyList (list) :
        def __new__(cls, *args, **kwargs) :
        return list.__new__(cl s, *args, **kwargs)

        or __init__ to pass values to a newly created immutable, eg

        class MyTuple (tuple) :
        def __init__(self, *args, **kwargs) :
        return super(tuple, self).__init__( *args, **kwargs)

        can't you? What's the pitfall?

        Comment

        • Duncan Booth

          #5
          Re: Question: Inheritance from a buil-in type

          afriere@yahoo.c o.uk (Asun Friere) wrote in
          news:38ec68a6.0 309300022.3c8e3 304@posting.goo gle.com:
          [color=blue]
          > Duncan Booth <duncan@NOSPAMr cp.co.uk> wrote in message
          > news:<Xns9405A0 1F17467duncanrc pcouk@127.0.0.1 >...
          >[color=green]
          >>
          >> 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).
          >>[/color]
          >
          > What is the thinking behind that? I mean you /can/ pass initial values
          > to a mutable using __new__, eg
          >
          > class MyList (list) :
          > def __new__(cls, *args, **kwargs) :
          > return list.__new__(cl s, *args, **kwargs)
          >
          > or __init__ to pass values to a newly created immutable, eg
          >
          > class MyTuple (tuple) :
          > def __init__(self, *args, **kwargs) :
          > return super(tuple, self).__init__( *args, **kwargs)
          >
          > can't you? What's the pitfall?
          >[/color]
          The pitfall is that these aren't doing what you think. In both cases you
          just passed the original arguments straight through, so the list also got
          the arguments it expected in its __init__ method, and the tuple got its
          expected arguments in __new__. If you modify the arguments in any way
          you'll find that your code still only sees the original arguments.

          list.__init__ and tuple.__new__ act on their arguments.
          list.__new__ and tuple.__init__ ignore their arguments.

          Take the tuple example. tuple() takes 0 or 1 arguments, so you can't write:

          tuple(1, 2, 3)

          So define a class to do this:
          [color=blue][color=green][color=darkred]
          >>> class MyTuple(tuple):[/color][/color][/color]
          def __new__(cls, *args):
          return tuple.__new__(c ls, args)

          [color=blue][color=green][color=darkred]
          >>> MyTuple(1, 2, 3)[/color][/color][/color]
          (1, 2, 3)

          Now try this with __init__ and the default __new__ will complain:
          [color=blue][color=green][color=darkred]
          >>> class MyTuple(tuple):[/color][/color][/color]
          def __init__(self, *args):
          tuple.__init__( self, args)

          [color=blue][color=green][color=darkred]
          >>> MyTuple(1, 2, 3)[/color][/color][/color]
          Traceback (most recent call last):
          File "<pyshell#7 3>", line 1, in ?
          MyTuple(1, 2, 3)
          TypeError: tuple() takes at most 1 argument (3 given)


          If you try subclassing list, then this example shows clearly that the
          arguments to __new__ are actually ignored:
          [color=blue][color=green][color=darkred]
          >>> class MyList (list) :[/color][/color][/color]
          def __new__(cls, *args, **kwargs) :
          return list.__new__(cl s, *args, **kwargs)
          def __init__(self, *args, **kwargs):
          print "list before init",self
          list.__init__(s elf, *args, **kwargs)

          [color=blue][color=green][color=darkred]
          >>> print MyList([1, 2, 3])[/color][/color][/color]
          list before init []
          [1, 2, 3]


          --
          Duncan Booth duncan@rcp.co.u k
          int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
          "\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?

          Comment

          Working...