Inherit from array

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

    #1

    Inherit from array

    Hi there.

    I'm trying to create a simple class called Vector which inherit from
    array.

    class Vector(array):
    def __init__(self,l ength):
    """initiali ze a vector of random floats of size length. floats
    are in interval [0;1]"""
    array.__init__( self,'f')
    for _ in xrange(length):
    self.apprend(ra ndom())

    but then :[color=blue][color=green][color=darkred]
    >>> v = Vector(10)[/color][/color][/color]
    TypeError: array() argument 1 must be char, not int

    Well, I guess it means array's __init__ method is not called with
    proper arguments ... It seems there is a problem with __init__
    overloading, like when I call Vector(x), it directly calls __init__
    method from array rather than the one defined in Vector class. Anyone
    got an idea on this ?

  • bruno at modulix

    #2
    Re: Inherit from array

    TG wrote:[color=blue]
    > Hi there.
    >
    > I'm trying to create a simple class called Vector which inherit from
    > array.[/color]

    Which array ?

    bruno@bousin ~ $ python
    Python 2.4.2 (#1, Feb 9 2006, 02:40:32)
    [GCC 3.4.5 (Gentoo 3.4.5, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
    Type "help", "copyright" , "credits" or "license" for more information.[color=blue][color=green][color=darkred]
    >>> array[/color][/color][/color]
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    NameError: name 'array' is not defined


    --
    bruno desthuilliers
    python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
    p in 'onurb@xiludom. gro'.split('@')])"

    Comment

    • TG

      #3
      Re: Inherit from array

      from array import array
      class Vector(array):
      def __init__(self,s ize):
      print "pouet"
      array.__init__( 'f')
      print "pouet"

      v = Vector('c')
      print repr(v)

      will output :

      pouet
      pouet
      array('c')

      Comment

      • Philippe Martin

        #4
        Re: Inherit from array

        I think he did

        from array import *


        Philippe




        bruno at modulix wrote:
        [color=blue]
        > TG wrote:[color=green]
        >> Hi there.
        >>
        >> I'm trying to create a simple class called Vector which inherit from
        >> array.[/color]
        >
        > Which array ?
        >
        > bruno@bousin ~ $ python
        > Python 2.4.2 (#1, Feb 9 2006, 02:40:32)
        > [GCC 3.4.5 (Gentoo 3.4.5, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
        > Type "help", "copyright" , "credits" or "license" for more information.[color=green][color=darkred]
        >>>> array[/color][/color]
        > Traceback (most recent call last):
        > File "<stdin>", line 1, in ?
        > NameError: name 'array' is not defined
        >
        >
        > --
        > bruno desthuilliers
        > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
        > p in 'onurb@xiludom. gro'.split('@')])"[/color]

        Comment

        • TG

          #5
          Re: Inherit from array

          Obviously, there is something I didn't catch in python's inheritance.

          from array import array
          class Vector(array):
          def __init__(self,s ize):
          print self.typecode
          array.__init__( self,'f')
          [color=blue][color=green][color=darkred]
          >>> v = Vector('c')[/color][/color][/color]
          c

          Here, it says the typecode is 'c' - I thought such an information was
          initalized during the array.__init__( self,'f') but obviously I was
          wrong.

          Maybe the typecode is defined before, during the call to __new__ method
          .... But here i'm getting lost.

          Comment

          • bruno at modulix

            #6
            Re: Inherit from array

            TG wrote:[color=blue]
            > Obviously, there is something I didn't catch in python's inheritance.[/color]

            Nope. Obviously, array.array doesn't respect the usual rules.
            [color=blue]
            > from array import array
            > class Vector(array):
            > def __init__(self,s ize):
            > print self.typecode
            > array.__init__( self,'f')
            >
            >[color=green][color=darkred]
            >>>>v = Vector('c')[/color][/color]
            >
            > c
            >
            > Here, it says the typecode is 'c' - I thought such an information was
            > initalized during the array.__init__( self,'f') but obviously I was
            > wrong.
            >
            > Maybe the typecode is defined before, during the call to __new__ method[/color]

            I think this must be something along this line.
            [color=blue]
            > ... But here i'm getting lost.
            >[/color]
            Let's see :

            from array import array

            class Vector(array):
            def __new__(cls, size):
            v = super(Vector, cls).__new__(cl s, 'f')
            #print "v is %s" % v
            return v
            def __init__(self, size):
            self.size = size

            v = Vector(42)
            print v


            HTH
            --
            bruno desthuilliers
            python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
            p in 'onurb@xiludom. gro'.split('@')])"

            Comment

            • bruno at modulix

              #7
              Re: Inherit from array

              Philippe Martin wrote:[color=blue]
              >
              > bruno at modulix wrote:[color=green]
              >>TG wrote:
              >>[color=darkred]
              >>>Hi there.
              >>>
              >>>I'm trying to create a simple class called Vector which inherit from
              >>>array.[/color]
              >>
              >>Which array ?[/color]
              >
              > I think he did
              >
              > from array import *
              >
              >[/color]

              oops ! Sorry, I forgot this was in the standard lib (well, I never used
              this module, so....)

              --
              bruno desthuilliers
              python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
              p in 'onurb@xiludom. gro'.split('@')])"

              Comment

              • Sion Arrowsmith

                #8
                Re: Inherit from array

                TG <girodt@gmail.c om> wrote [something like]:[color=blue]
                >from array import array
                >class Vector(array):
                > def __init__(self,s ize):
                > array.__init__( 'f')
                >
                >v = Vector('c')
                >print repr(v)
                >
                >will output :
                >
                >array('c')[/color]

                Is this a case of new-sytle classes being confusing? Because
                I'm certainly confused. I guess what's needed is:

                class Vector(array):
                def __new__(cls, size):
                self = array.__new__(a rray, 'f')
                ...
                return self

                But how does one determine what classes need to have __init__
                overridden and which __new__ when subclassing?

                --
                \S -- siona@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
                ___ | "Frankly I have no feelings towards penguins one way or the other"
                \X/ | -- Arthur C. Clarke
                her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

                Comment

                • bruno at modulix

                  #9
                  Re: Inherit from array

                  Sion Arrowsmith wrote:[color=blue]
                  > TG <girodt@gmail.c om> wrote [something like]:[color=green]
                  >>from array import array[/color]
                  >[color=green]
                  >>class Vector(array):
                  >> def __init__(self,s ize):
                  >> array.__init__( 'f')
                  >>
                  >>v = Vector('c')
                  >>print repr(v)
                  >>
                  >>will output :
                  >>
                  >>array('c')[/color]
                  >
                  >
                  > Is this a case of new-sytle classes being confusing?[/color]

                  Nope. FWIW, array is coded in C, and seems not to follow all standard
                  conventions...
                  [color=blue]
                  > Because
                  > I'm certainly confused. I guess what's needed is:
                  >
                  > class Vector(array):
                  > def __new__(cls, size):
                  > self = array.__new__(a rray, 'f')
                  > ...
                  > return self[/color]

                  Yes.
                  [color=blue]
                  > But how does one determine what classes need to have __init__
                  > overridden and which __new__ when subclassing?[/color]

                  It's the first exemple I see of a mutable type needing this.

                  NB :

                  """
                  __new__() is intended mainly to allow subclasses of immutable types
                  (like int, str, or tuple) to customize instance creation.
                  """

                  Usually, overriding __init__ is the way to go.

                  --
                  bruno desthuilliers
                  python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                  p in 'onurb@xiludom. gro'.split('@')])"

                  Comment

                  • TG

                    #10
                    Re: Inherit from array

                    Hmm ... I'm definitely not a python wizard, but it seems to be quite a
                    special case that breaks the rules ... unpythonic, isn't it ?

                    Has anyone seen a PEP on this subject ?

                    Just in case a troll reads this message : i'm not saying python sucks
                    or has huge design flaws here ...

                    Comment

                    • bruno at modulix

                      #11
                      Re: Inherit from array

                      TG wrote:[color=blue]
                      > Hmm ... I'm definitely not a python wizard, but it seems to be quite a
                      > special case that breaks the rules ...[/color]

                      Yes and no. The primary use case for __new__ was to allow subclassing of
                      immutable types. array.array is not immutable, but it's still a special
                      case, in that it enforce type-based restrictions.

                      I guess that it does so by creating different types based on the
                      typecode (this is low-level, C stuff), so this can only happen in the
                      constructor (the object is already created when the initializer is called).
                      [color=blue]
                      > unpythonic, isn't it ?[/color]

                      Not really -> practicallity beats purity !-)

                      But this should definitively be documented. I don't have time to do so
                      right now - anybody willing to take care of this ?


                      --
                      bruno desthuilliers
                      python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
                      p in 'onurb@xiludom. gro'.split('@')])"

                      Comment

                      • Scott David Daniels

                        #12
                        Re: Inherit from array

                        bruno at modulix wrote:[color=blue]
                        > TG wrote:[color=green]
                        >> Hmm ... I'm definitely not a python wizard, but it seems to be quite a
                        >> special case that breaks the rules ...[/color]
                        >
                        > Yes and no. The primary use case for __new__ was to allow subclassing of
                        > immutable types. array.array is not immutable, but it's still a special
                        > case, in that it enforce type-based restrictions.[/color]
                        The alternative is to either:
                        1) Allow arrays that have no type.
                        or 2) Allow arrays that change type.
                        Neither is a tasty alternative. __new__ sets the stuff that
                        must be invariant (and for an array, that is the element type),
                        and __init__ does any further initialization (initialization
                        should be re-runnable). In the case of array, filling the array
                        with data seems a great use of __init__.


                        --
                        -Scott David Daniels
                        scott.daniels@a cm.org

                        Comment

                        Working...