1

I want to define a class and create an object instance. But always get error. The code goes like this:

class complex:
    def _init_(self,realpart,imagpart):
        self.r=realpart
        self.i=imagpart

x=complex(3,4)

the error message is:

Traceback (most recent call last):<br>
  File "pyshell#5", line 1, in "module" <br>
  x=complex(3,4) <br>
  TypeError: object.__new__() takes no parameters

so what is the problem?

thanks for your reading!

2
  • it should be __init__ not _init_ Commented Feb 20, 2013 at 4:25
  • Python has native support for complex numbers. 3+4j for example Commented Feb 20, 2013 at 4:26

2 Answers 2

2

_init_ should have two underscores on each side:

>>> class complex:
...     def __init__(self,realpart,imagpart):
...         self.r=realpart
...         self.i=imagpart
... 
>>> x=complex(3,4)

Also, just so you know, Python already has a complex type:

>>> 2+3j
(2+3j)
>>> complex(2, 3)
(2+3j)
Sign up to request clarification or add additional context in comments.

Comments

1

__init__ supposed to have 2 underscores surrounding it rather than 1

So

def _init_(self,realpart,imagpart):

should be

def __init__(self,realpart,imagpart):
  • One more suggesting, instead of multiple assignments, tuple unpacking would be more readable and marginally efficient

  • Prefer new Type Class construct, which derives from object

  • PEP8 suggests to use CamelCase for Class Names

  • Always use the batteries if available instead of rolling your own. Python already supports complex types by default

SO here it goes

class complex(object):
    def __init__(self,realpart,imagpart):
        self.r, self.i=realpart, imagpart

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.