简体   繁体   中英

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM