检查给定对象是否属于给定类型的最佳方法是什么?如何检查对象是否继承给定类型?
假设我有一个对象o.我如何检查它是否是一个str?
我经常从我的 Python 代码中得到未捕获的异常(错误),这些异常被描述为TypeErrors. 经过大量的实验和研究,我收集了以下示例(以及细微的变化):
TypeError: func() takes 0 positional arguments but 1 was given
TypeError: func() takes from 1 to 2 positional arguments but 3 were given
TypeError: func() got an unexpected keyword argument 'arg'
TypeError: func() missing 1 required positional argument: 'arg'
TypeError: func() missing 1 required keyword-only argument: 'arg'
TypeError: func() got multiple values for argument 'arg'
TypeError: MyClass() takes no arguments
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: can only concatenate str …Run Code Online (Sandbox Code Playgroud) 我目前正在使用一个Arduino整数(int)通过串行(使用pySerial)输出到我正在编写的Python脚本,Arduino以便与X-Plane飞行模拟程序进行通信.
我设法将原始文件分成两个字节,以便我可以将它发送到脚本,但是我在重建原始整数时遇到了一些麻烦.
我尝试使用基本的按位运算符(<<,>>等),就像我在类似C++的程序中所做的那样,但它似乎没有用.
我怀疑它与数据类型有关.我可能在相同的操作中使用带有字节的整数,但我无法确定每个变量的类型,因为你并不真正在Python中声明变量,据我所知(我对Python很新) .
self.pot=self.myline[2]<<8
self.pot|=self.myline[3]
Run Code Online (Sandbox Code Playgroud) 所以给了我一个列表,我必须打印列表中每个项目的类型.我可以清楚地看到有字符串和整数,但我需要它在Python中打印出来.我们刚刚学习了循环,所以我觉得这就是他们正在寻找的东西,但我无法打印出来.
我有一个变量 f。我如何确定它的类型?这是我的代码,输入到 python 解释器中,显示使用我在 Google 上找到的许多示例的成功模式时出现错误。(提示:我对 Python 非常陌生。)
>>> i=2; type(i) is int
True
>>> def f():
... pass
...
>>> type(f)
<class 'function'>
>>> type(i)
<class 'int'>
>>> type(f) is function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> f=3
>>> type(f) is int
True
Run Code Online (Sandbox Code Playgroud)
使用 fa 函数,我尝试将 type(f) 的返回值转换为字符串,其中 u = str(type(f))。但是当我尝试 u.print() 时,我收到一条错误消息。这对我提出了另一个问题。在 Unix 下,来自 Python 的错误消息会出现在 stderr 或 stdout 上吗?
我正在查看python中的函数的在线文档round(),其中说,
round(number[, ndigits])....如果使用一个参数调用,则返回值为整数,否则与数字类型相同.
所以,我写了下面的代码.
x = round(32.7)
print 'x is now : ', x
print str(type(x))
print type(x).__name__
Run Code Online (Sandbox Code Playgroud)
让我解释一下我在上面的代码片段中使用的最后两个打印件.
令人惊讶的是,目前的输出是
x现在是:33.0
<type'float'>
float
我在期待
x现在是:33
<type'int'>
int
我没有想法.我错过了什么?
PS对于任何有兴趣的人,a LIVE VERSION