1

I want to make a new class that is both a float type and has some custom attributes as follows

class Father:
    def __init__(self, a: float, b: str):
        self.a = a
        self.b = b
        print('Father', a, b)


class Son(Father, float):
    def __init__(self, a, b):
        super(Son, self).__init__(a, b)

if __name__ == '__main__':
    son = Son(1, "b")
    print(son.a)

but it reports

TypeError: float expected at most 1 arguments, got 2

I have tried to modified the class Son as follows but it doesn't work.

class Son(Father, float):
    def __init__(self, a, b):
        Father.__init__(a, b)
        float.__init__(self)

Also, the following code reports the same error, but I don't know why.

class Son(float):
    def __init__(self, a, b):
        super(Son, self).__init__(self)

if __name__ == '__main__':
    son = Son(1, "b")
    print(son)
david
  • 842
  • 2
  • 8
  • 25

1 Answers1

2

So, because you inherit from float you must handle __new__:

class Father:
    def __init__(self, a: float, b: str):
        self.a = a
        self.b = b
        print('Father', a, b)


class Son(Father, float):
    def __new__(cls, a, b):
        # float.__new__ requires a single arugment
        return super().__new__(cls, a)
    def __init__(self, a, b):
        super().__init__(a, b)

if __name__ == '__main__':
    son = Son(1, "b")
    print(son.a)

But you should really consider if instead of inheritance you should be using composition or another approach. Why inherit from float?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172