This article is based on the discussion in this page: http://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python
From this page, it has the following code sample.
# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None
Also , the author commented that
S.Lott 写道
First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.
However, if the type comparison is what you really wants, (they must be some case when it is needed), you can do as above.
I am attaching the example that I am having for check the type of parameter to a certain function.
def check(n, p, a=None):
"""
:param n: the # of instance to start
:param p: the path to the Command/Script to start
:param a: this is optional argument,
"""
assert(n is not None and n > 0)
assert(p is not None and p != "")
assert(a is None or a != "")
if (not isinstance(n, int)): raise TypeError("Argument 'n' expect integer")
if (n is None or n <= 0): raise ValueError("Argument 'n' invalid");
if (a is not None):
if (type(a) != StringType): raise TypeError("Argument 'a': expect string")
if (type(a) is not StringType): raise TypeError("Argument 'a': expect string")
if (type(a) != str): raise TypeError("Argument 'a': expect string")
if (type(a) is not str): raise TypeError("Argument 'a': expect string")
# while this is wrong, because is is like identity equal operator
# it is like
# a is b
# is equivalent
# id(a) == id(b)
#
# if (a is not str): raise TypeError("Argument 'a': expect string")
if (not isinstance(a, str)): raise TypeError("Argument 'a': expect string")
if (not (type(a) in [str, unicode])): raise TypeError("Argument 'a': expect string")
pass
分享到:
相关推荐
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...
4. **比较运算符(Comparison Operators)**: 包括`==`, `!=`, `, `>`, `, `>=`,用于比较值。 5. **逻辑运算符(Logical Operators)**: `and`, `or`和`not`用于组合条件。 6. **组合查询(Composing Queries)**...
They do not need to be declared explicitly and can be assigned any data type. **Numbers and Math** Python supports basic arithmetic operations such as addition (+), subtraction (-), multiplication ...
在本资源中,我们关注的是C、Java和Python这三种流行的编程语言的BNF范式。 首先,让我们详细探讨C语言的BNF范式。C语言的语法严谨且层次分明,它的BNF范式主要涵盖了程序的基本组成部分,如声明(declarations)、...
'ComparisonOperator': 'GREATER_THAN', 'Threshold': 80, 'ThresholdType': 'PERCENTAGE' }, 'Subscribers': [ { 'SubscriptionType': 'SNS', 'Address': 'arn:aws:sns:us-east-1:123456789012:MyTopic' }...
4. **Default Comparison Operators:** Python 3 no longer provides a default implementation for `, `, `>`, and `>=` operators. Implementations must be explicitly defined. 5. **Numeric Changes:** ...
- `l.sort(f)`: Sorts the list using the comparison function `f` (default is `cmp`). - **Dictionary Operations:** - `d = {'x': 42, 'y': 3.14, 'z': 7}`: Creates a dictionary. - `d['x']`: Retrieves ...
4. **配对和比较(Blocking and Comparison)**:使用选定的特征和阈值,将数据集划分为较小的块,然后在每个块内比较记录,减少不必要的比较。 5. **验证和标记(Validation and Labeling)**:用户可以介入,对...
comparison=ce.ComparisonOperator.GREATER_THAN, notification_types=[ce.NotificationType电子邮件], recipients=["example@example.com"], ) ], ) ``` 以上代码创建了一个500美元的成本预算,如果费用超过...
- Converting integers to strings for comparison. 18. **Final Line** - **Objective:** Read a text file and print the final line. - **Key Concepts:** - File handling using `open()`. - Reading ...
6. 比较运算符(comparison operators on int, float, string):在Python中,比较运算符用于比较两个值,并返回一个布尔值。常见的比较运算符包括等号(==)、不等号(!=)、大于(>)、小于(<)、大于等于(>=)和小于等于()...
10. **unidiomatic-typecheck (C0123)**: 使用`type()`进行类型检查时,pylint建议改用`isinstance()`,因为后者是Python中更为标准的做法。 11. **consider-using-enumerate (C0200)**: 当检测到代码使用`range`和...
o DBMS functions output comparison o DBMS specific features such as MySQL comment injection o Passive SQL injection fuzzing * It fully supports two SQL injection techniques: o Blind SQL injection,...
- **比较运算符(Comparison Operators)** - `=`: 等于 - `<>` 或 `!=`: 不等于 - `小于 - `>`: 大于 - `小于等于 - `>=`: 大于等于 - **数学运算符(Mathematical Operators)** - `+`: 加法 - `-`: 减法 - `...
This demo presents a visual comparison between SAX and PAA and shows how SAX can represent data in finer granularity while using the same, if not less, amount of space as PAA. The input parameter ...
15.10 A Comparison of Functional and Imperative Languages 653 Summary • Bibliographic Notes • Review Questions • Problem Set • Programming Exercises 654 Chapter 16 Logic Programming Languages...
collision 碰撞 冲突 column 列 列 comment 注解、注释 注释 comparison operator 比较运算子 比较操作符(如 ==, <) compiler 编译器 编译器 compile-time error 编译时期错误 编译时错误 component 组件 ...
1. **动态类型(Dynamic Type)**:C# 4.0引入了动态类型,允许在运行时确定变量的实际类型。`dynamic`关键字用于声明变量,使得代码在编译时不进行类型检查,而是在运行时进行。这为与动态语言如Python或JavaScript...