Today, I looked at the website of Liao Xuefeng, and found that there is a isinstance function that can judge the type of the parameter:
Check the parameter type to allow only integers and floating-point type parameters. Data type checking can be implemented with built-in functions isinstance
:
def my_abs (x): If not isinstance (x, (int., float)): Raise TypeError (' bad operand type ') if x >= 0:r Eturn x else:return-x
Once the parameter check has been added, the function can throw an error if it passes in the wrong parameter type:
>>> my_abs (' A ') Traceback (most recent): File "<stdin>", line 1, in <module> File "<std In> ", line 3, in My_abstypeerror:bad operand type
Throwing exceptions using raise
When an error occurs in the program, Python automatically throws an exception, or it can throw an exception by raise the display. Once the raise statement is executed, the statement following the raise cannot be executed
From
Http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 00137473843313062a8b0e7c19b40aa8f31bdc4db5f6498000
Python isinstance function raise