Raise TypeError for invalid input value in class
I am trying to write class
, and I want that if the initial input values ββfor a class are not obeying certain types, this would throw an exception. For example, I would use except TypeError
to return an error. I don't know how this should be done. My first attempt at writing the class
following:
class calibration(object):
def __init__(self, inputs, outputs, calibration_info, interpolations=2):
try:
self.inputs=inputs
except TypeError
self.outputs=outputs
self.cal_info=calibration_info
self.interpol=interpolations
I would like if the value is inputs
not a string it throws an error message. I would appreciate any help.
source to share
Its slightly different between 2.x and 3.x, but use isinstance to determine the type and then throw an exception if you are not satisfied.
class calibration(object):
def __init__(self, inputs, outputs, calibration_info, interpolations=2):
if not isinstance(inputs, basestring):
raise TypeError("input must be a string")
Python2 distinguishes between ascii and unicode strings - "basestring" swaps both of them. There are only unicode strings in python3 and you are using 'str' instead.
source to share