Need help with syntax on inheritance.

Peter Otten __peter__ at web.de
Wed Oct 4 10:20:37 CEST 2006


SpreadTooThin wrote:

> If you are deriving a new class from another class,
> that you must (I assume) know the initializer of the other class.
> 
> So in myClass
> 
> import array
> class myClass(arrary.array):
>    def __init__(self, now here I need to put array's constructor
> parameters..., then mine):
>       array.array.__init__(self, typecode[, initializer])
>       self.mine = mine
> 
> So I'm confused...
> array has a typecode parameter and an optional initiializer...
> So could you help me with the class construction here please?

Normally you would do 

# won't work
class Array(array.array):
    def __init__(self, typecode, initalizer=(), mine=None):
        array.array.__init__(self, typecode, initializer)
        self.mine = mine

However, array.array is a bit harder to subclass:

# should work
class Array(array.array):
    def __new__(cls, typecode, initializer=(), mine=None):
        return array.array.__new__(cls, typecode, initializer)
    def __init__(self, typecode, initializer=(), mine=None):
        array.array.__init__(self, typecode, initializer) 
        self.mine = mine

See if you can get away by making the array an attribute of your class
instead.

Peter



More information about the Python-list mailing list