I am trying to write a class
and I want that if the initial input values for the class don't obey specific types, it would raise an exception. For instance I would use except TypeError
to return an error. I don't know how it should be done though. My first attempt to write the class
is as 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 that if inputs
value is not a string then it raises an error message. I would appreciate for any help.
Its a bit different between 2.x and 3.x, but use isinstance to figure out type and then raise the 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 differentiates between ascii and unicode strings - "basestring" convers them both. In python3, there are only unicode strings and you use 'str' instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With