上QQ阅读APP看书,第一时间看更新
The isinstance function
Similar to type, isinstance checks whether a variable is of a particular data type, structure, or class. This makes it very useful for testing purposes, or if you want to check arguments for the correct type:
>>> isinstance('Hello world', str)
True
Here, we checked whether the value is a string—and indeed it is! We can also pass multiple variable types, in which case isinstance will return True if the value matches any of the given types:
>>> isinstance(1, (int, float))
True
Note the second parenthesis, surrounding two value types we pass in. This parenthesis represents a tuple, one of the data structures, which we'll discuss in the next chapter.
Finally, there is dir, which is invaluable if we need to work with obscure, badly documented code.