0

This code does not work. Please tell what the error is....

class Error(Exception):
    def __init__(self,mssg):
        self.mssg = mssg

class InputError(Error):
    def __init__(self,val):
        super("Input Error")
        print val

Now I write in other part of my program

a = raw_input("Enter a number from 0-9: ")
if (ord(a)>47 and ord(a)<58):
    pass
else:
    raise InputError(a)

Now when I pass 'a' I get super expected a type but got a string I just want to pass that message to the base class and display it along with the wrong value.

What am I doing wrong here

4 Answers4

1

The problem is that you're using super() incorrectly. The proper way is:

class InputError(Error):
    def __init__(self, val):
        super(InputError, self).__init__(val)
        print val
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
brildum
  • 1,759
  • 2
  • 15
  • 22
  • 1
    It seems tricker, but it follows with other Python idioms. Just as methods require you to explicitly pass `self` (which is the current instance), `super` requires you to explicitly pass in the current class. – brildum Dec 16 '10 at 16:05
0

super() is used to access methods of a superclass that have been overridden in the subclass, not to instantiate the superclass with arguments.

What you appear to be trying to do is something like:

class InputError(Error):
    def __init__(self,val):
        super(InputError).__init__("Input Error")
        print val

although this isn't necessarily a good idea.

Wooble
  • 87,717
  • 12
  • 108
  • 131
  • Please tell how do you do it then.... lets say that there is a variable in base class and since it is common to all you want to just pass the value from the subclass what do you do?? –  Dec 16 '10 at 14:57
0

super is supposed to be called like this:

class InputError(Error):
    def __init__(self,val):
        super(InputError, self).__init__("Input Error")
        print val
Abhinav Sarkar
  • 23,534
  • 11
  • 81
  • 97
0

super is a python builtin which takes the type of an object as its argument, not some (arbitrary) string, as you seem to have done. You probably mean

 super(InputError, self).__init__("Input Error")

[In Python 3.x, this can just be super().__init__("Input Error")]

Note that because of the name of your exception is already InputError, it's not clear what the string message adds to it...

See this question and the python docs.

Community
  • 1
  • 1
Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • Yes It does .... Thanks a lot and I was referring to your saying that I am passing "Input Error" –  Dec 16 '10 at 15:38