ryanvolap
ryanvolap

Reputation: 77

Class: __new__ and __init__ in inherited class in Python

I have a class like this:

class FloatArray():
    def __init__(self):
        self.a = 1.5

    def __new__( cls, value ):
        data = (c_float * value)()
        return data

array_1 = FloatArray(9)
print(array_1)
>>>> __main__.c_float_Array_9 object at 0x102228c80>

Now I want to make a FloatArray4 class inherits from FloatArray class and the value a can be called.

Here is the code for the second class.

class FloatArray4( FloatArray ):
    def __init__(self):
        super(FloatArray, self).__init__()

    def printValue( self ):
        print(self.a)

I have problems:

First, I have to call array_2 = FloatArray4(4) which I don't want, I would like it to be called like this array_2 = FloatArray4(), But I don't know how.

Second, when I tried to call array_2.printValue() I got an error: AttributeError: 'c_float_Array_4' object has no attribute 'printValue'

Could any one please help?

Thanks.

Upvotes: 1

Views: 120

Answers (2)

Alexander Bolzhatov
Alexander Bolzhatov

Reputation: 298

c_float = 5

class FloatArray(object):
    def __init__(self, value):
        super(FloatArray, self).__init__()
        self.a = 1.5

    def __new__( cls, value ):
        obj = super(FloatArray, cls).__new__(cls)
        obj.data = c_float * value
        return obj

array_1 = FloatArray(9)

class FloatArray4(FloatArray):
    def __init__(self, value=4):
        super(FloatArray4, self).__init__(value)

    def __new__(cls, value=4):
        obj = super(FloatArray4, cls).__new__(cls, value)
        return obj

    def printValue( self ):
        print(self.a)

array_2 = FloatArray4()

array_2.printValue()

Upvotes: 0

jasonharper
jasonharper

Reputation: 9597

Your __new__() is returning an instance of an entirely unrelated class, which is an extremely unusual thing to do. (I'm honestly not sure why this is even allowed.) Your __init__() never gets called, and none of your methods or attributes are available, because the resulting object is not in any sense an instance of your class.

Upvotes: 4

Related Questions