0

I am working on a project where I need to deal with complex numbers. I am using the predefined class complex in python. But I would like to add some more properties to the predefined implementation.

I tried to inherit the class through a custom class, like this

class C(complex):
    def __init__(self,x,y):
        complex.__init__(self,x,y)

But it shows the error

TypeError: object.__init__() takes exactly one argument (the instance to initialize)

Can anyone suggest the proper way to inherit from class complex in python? Thanks!!

  • 2
    Does this answer your question? [Subclassing int in Python](https://stackoverflow.com/questions/3238350/subclassing-int-in-python) It is basically the same, even though the built-in type is int in that question. – Rodrigo Rodrigues Jan 02 '20 at 17:02
  • An `__init__` which just calls the superclass might as well not be there. – quamrana Jan 02 '20 at 17:11

3 Answers3

2

It might be easier, to keep the class arguments as they are:

class C(complex):
    def __new__(cls, *args, **kwargs):
        return complex.__new__(cls, *args, **kwargs)

c = C()
print(c)
d = C(1, 2)
print(d)

Output:

0j
(1+2j)
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
1

You need to initialize complex using super() which doesn't take any additional arguments, like this:

class C(complex):
    def __init__(self, x, y):
        super().__init__()

Edit:

Or simply

class C(complex):
    '''No need of defining any constructors'''
    ...
    def someOtherMethod(*args,**kargs):
        pass

Ie. to inherit built in classes one need not define nay constructors.

youessbeesee
  • 26
  • 1
  • 2
  • Yes you are right, no need to actually re-implement the constructor. I assumed that was wanted because of the provided example, and it is a common thing to do when subclassing. – youessbeesee Jan 03 '20 at 21:09
0

You need to call the super class.

class C(complex):
    def __init__(self,x,y):
        super(C, self).__init__()

complexNumber = C(1,2)
print(complexNumber)
# (1+2j)
Vasco Lopes
  • 141
  • 9
  • You ignore params `x,y`, so what is the point of it? – quamrana Jan 02 '20 at 17:14
  • @quamrana, as complex class receives 2 variables, x and y will automatically be treated by the constructor. Run the code and check that it works. If you wish, you can do stuff with the x and y in the C class init – Vasco Lopes Jan 02 '20 at 17:15
  • 1
    I mean, there is no difference between what you have and `class C(complex): pass`. – quamrana Jan 02 '20 at 17:20