* Alf P. Steinbach:
* Torsten Mohr:
Hello,
i try to derive a class from array.array:
import array
class Abc(array.array):
def __init__(self, a, b):
array.array.__init__(self, 'B')
self.a = a
self.b = b
a = Abc(4, 5)
print a
print a.a
I get an error for "a = Abc(4, 5)", seems the parameters are
forwarded to array's __init__ as they are.
No, with CPython they're forwarded to __new__.
Though i explicitly
call __init__() for array.
That's the constructor inherited from 'object', it takes no args (except
the self arg).
I'd like to use array and make sure it's type is always 'B'.
I'd like to derive because i don't want to rewrite all the methods
like __getiem__ for my class and then call array's __getitem__.
How do i best derive from array.array?
<code>
import array
class ByteArray( array.array ):
def __new__( self, *args ):
return array.array.__new__( self, "B" )
def __init__( self, a, b ):
array.array.__init__( self )
self.a = a
self.b = b
a = ByteArray( 4, 5 )
print( a )
print( a.a )
</code>
Disclaimer: I'm not a Python programmer. :-)
Hm, good that I included a disclaimer. The above code is technically OK but it
is misleading. The first argument to '__new__' is not a self argument but a type
argument, better called 'cls' or some such.
From the docs, "__new__() is a static method (special-cased so you need not
declare it as such) that takes the class of which an instance was requested as
its first argument"
Cheers,
- Alf (self-correcting)
--
http://mail.python.org/mailman/listinfo/python-list