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
  • 2
    Does this answer your question? Subclassing int in Python It is basically the same, even though the built-in type is int in that question. Commented Jan 2, 2020 at 17:02
  • An __init__ which just calls the superclass might as well not be there. Commented Jan 2, 2020 at 17:11

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I can't get your code to work. object.__init__() complains.
Ok, but your answer is now the same as the duplicate.
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.

1 Comment

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

3 Comments

You ignore params x,y, so what is the point of it?
@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
I mean, there is no difference between what you have and class C(complex): pass.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.