如何确定Python中文字的类型?
How to determine literal's type in Python?
在Ruby中,可以使用.class
来判断文字的类型。例如:
100.class
=> Fixnum
"Hi".class
=> String
3.14.class
=> Float
[1, 2, 3].class
=> Array
{:name => "John"}.class
=> Hash
如何在 Python 中做同样的事情?我知道什么是文字和 Python 文字语法。我只是想知道是否有办法让我确定它。提前致谢。
使用type(expression)
判断表达式的类型
使用type()
:
>>> type(2)
<class 'int'>
>>> type(2.2)
<class 'float'>
>>> type(100)
<class 'int'>
>>> type("hi")
<class 'str'>
>>> type(3.14)
<class 'float'>
>>> type([1,2,3])
<class 'list'>
>>> type({'a': 1})
<class 'dict'>
您可以使用 type
,如前所述 - 但此功能用于检查目的,主要用于 repl/shell/console 等
我的意思是,写这样的东西,
if type(a) == int:
do_something()
不是 pythonic。
出于这种目的,请使用 isinstance(variable, class_name)
,它更 pythonic 也更有意义。我使用有意义的是因为,作为对象 based/oriented 语言,python 没有类型,至少你应该假装它没有类型。您创建的每个对象,或作为您创建的过程的输出而生成的每个对象都是某些 类 的实例 - 至少您应该这样处理 python。
在Ruby中,可以使用.class
来判断文字的类型。例如:
100.class
=> Fixnum
"Hi".class
=> String
3.14.class
=> Float
[1, 2, 3].class
=> Array
{:name => "John"}.class
=> Hash
如何在 Python 中做同样的事情?我知道什么是文字和 Python 文字语法。我只是想知道是否有办法让我确定它。提前致谢。
使用type(expression)
判断表达式的类型
使用type()
:
>>> type(2)
<class 'int'>
>>> type(2.2)
<class 'float'>
>>> type(100)
<class 'int'>
>>> type("hi")
<class 'str'>
>>> type(3.14)
<class 'float'>
>>> type([1,2,3])
<class 'list'>
>>> type({'a': 1})
<class 'dict'>
您可以使用 type
,如前所述 - 但此功能用于检查目的,主要用于 repl/shell/console 等
我的意思是,写这样的东西,
if type(a) == int:
do_something()
不是 pythonic。
出于这种目的,请使用 isinstance(variable, class_name)
,它更 pythonic 也更有意义。我使用有意义的是因为,作为对象 based/oriented 语言,python 没有类型,至少你应该假装它没有类型。您创建的每个对象,或作为您创建的过程的输出而生成的每个对象都是某些 类 的实例 - 至少您应该这样处理 python。