4

x = [1,2,3]

然后在ipython,我得到以下

> In [8]: type(x) 
Out[8]: list
> 
> In [9]: print(type(x)) 
<class 'list'>

为什么不 print(type(x)) 只是打印列表,而不是额外的类的东西?

一个相关的问题是,如何显示输出

type of x is; list

print(' type of x is: ', type(x)) 不这样做是因为我得到了额外的课程内容,例如

In [2]: print(' type of x is: ', type(x))
 type of x is:  <class 'list'>
4

4 回答 4

1

正如 pwxcoo 所说,这为Ipython您做了一些额外的工作,请在普通的 python shell 中尝试它,除非您明确显示,否则它不会显示任何内容print()

于 2018-10-19T06:04:28.377 回答
0

我测试type(x)。它会一直输出<class 'list'>。您直接获得的原因list是 IPython 为您做了额外的工作。

使用type()将返回类型对象。操作它并使用__name__.

print(' type of x is: ', type(x).__name__)
#  type of x is: list
于 2018-10-19T05:56:16.660 回答
0

我肯定会按照 pwxcoo 显示的方式这样做。在我知道 __ name __ 是类型的属性之前,我通过将类型转换为字符串并将其切片来做到这一点:

str(type(x)).split()[1][1:-2]

所以这是一个很好的提醒,你可以运行 dir(type) 并看到 __ name __ 是一个属性,所以你不必做我做过的丑陋的事情!

于 2018-10-19T06:10:15.403 回答
0

来自文档:https ://docs.python.org/2/library/functions.html#type

类类型(对象)

使用一个参数,返回对象的类型。返回值是一个类型对象。建议使用 isinstance() 内置函数来测试对象的类型。

获取类名可以参考特殊属性获取__name__

print(type(x).__name__)

您可以__name__在此处的文档中找到更多信息:https://docs.python.org/2/library/stdtypes.html#definition。姓名

于 2018-10-19T06:11:11.580 回答