在Python中这是什么?(类型相关)

2024-04-25 01:58:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还比较陌生,我在上课。你知道吗

我是这样做的:

>>> x = int()
>>> x
0
>>> type(x)
<type 'int'>
>>> x = str()
>>> type(x)
<type 'str'>
>>> x = tuple
>>> type(x)
<type 'type'>
>>> x = ()
>>> type(x)
<type 'tuple'>
>>> x = blak
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'blak' is not defined

为什么将tuple赋值给一个新创建的变量会给它一个type类型,而不是给它一个元组类型?(我同意它不给出tuple类型,因为x = ()这样做了。) 任何其他的词,它(显然)给出了一个错误。你知道吗

我在这里碰到了什么?我在文档中找不到任何东西,因为搜索引擎没有真正的帮助。你知道吗

还有,现在我看看 x = strx = int

也会导致

type(x) = int

同样地


Tags: 类型mosttypestdinlinecallfileint
3条回答

其他人已经指出了原因,但我将设法填补一些空白。你知道吗

在Python中,所有内容都是“一流的”。这意味着您可以将示例函数和类型赋给变量,并将它们用作原始值:

def function(): pass
class Class(object): pass

x = function
x()

y = Class
instance = y()

这就是为什么您能够将元组赋给变量的原因。有关详细信息,请参见post by Guido van Rossum。你知道吗

关于类型,这可能真的很混乱。tupletype的实例(与1int的实例的关系相同)。换句话说,它的类型是typetype用于创建type的实例或确定其类型(type的实例):

x = 1
# determine type
type(x)

# class statement
class A(object):
    pass

# equivavent to previous class statement
# creates a new class (in other words new "type", and in other words new instance of type)
B = type('B', (object, ), {})

这就是为什么tuple的类型是type。有关详细信息,请参阅我的blog post。或者在Python中使用google/bing作为元类。你知道吗

tuple是tuple类型的类型构造函数。其他此类类型构造函数在Python中的行为也类似:

>>> type(tuple)
>>> type(int)
>>> type(dict)
>>> type(str)

所有这些都将产生<type 'type'>。你知道吗

如果将这些类型作为函数调用,则可以获取实例,如下所示:

>>> type(tuple())
>>> type(tuple([1,2,3]))
>>> type(())

都会产生<type 'tuple'>。你知道吗

x = tuple是一个类型。x = tuple()将是一个元组。。。你知道吗

相关问题 更多 >