The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types
This paper mainly introduces three methods to judge the data type of user input when using Python Object Oriented programming, namely the type function, the isinstance function and regular expressions, and also presents the relevant syntax.
This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing of host computer and slave computer as application examples, and uses Sourcetrail code software for visual code reading to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
We can use three methods to determine the data type of user input: the type function, the isinstance function, and regular expressions.
Use the type () function to determine the data type
In Python, we can use the built-in function type () to determine the data type of a variable. The type () function returns an object that represents the data type, and we can judge the type of the variable by comparing this object with the target type. For example:
# Check whether the input port number is of type str
if type(port) is not str:
Use the isinstance () function to determine the data type
Besides the type () function, Python also provides another commonly used function isinstance () to determine the type of a variable. The isinstance () function can check whether a variable belongs to a specific type or its subtype. Its syntax format is: isinstance (object, classinfo), where object is the object to be judged, and classinfo can be a type object or a tuple of types. For example:
# Check whether the input port number is of type str
if isinstance(port, str):
Use Regular Expression to determine the data type
Regular Expression is a powerful tool that can be used to match and extract various patterns in strings. We can use Regular Expression to determine whether the data input by users conforms to a specific format, so as to infer the type of the data. For example:
if re.match(r'^[0-9]+$', user_input):
print("输入的是整数类型")