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

时间:2014-02-12 08:48:26

标签: python python-2.7 types

我在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类型,而不是给它一个元组类型? (我没有给它提供元组类型,因为x = ()这样做。) 任何其他单词和它(显然)都会出错。

我在这里偶然发现了什么?我在文档中找不到任何内容,因为搜索引擎并没有真正帮助。

此外,现在我看是否 x = str 要么 x = int

也导致

type(x) = int

同样

6 个答案:

答案 0 :(得分:2)

x = tuple是一种类型。 x = tuple()将是一个元组......

答案 1 :(得分:2)

其他人已经指出了原因,但我会尽量填补一些空白。

在Python中,一切都是“一流的”。这意味着您可以为变量分配示例函数和类型,并将它们用作原始值:

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

x = function
x()

y = Class
instance = y()

这就是为什么你能够将元组分配给变量的原因。有关详细信息,请参阅post by Guido van Rossum

现在关于类型,这可能真的令人困惑。 tupletype 的实例(与1相同的关系是int的实例)。换句话说,它的类型是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, ), {})

这就是元组类型为type的原因。有关详细信息,请参阅我的blog post。或者只是google / bing for Python中的元类。

答案 2 :(得分:0)

tuple是一种类型,因为str是一种类型。 tuple()()是一个元组。

答案 3 :(得分:0)

tuplex = tuple的类型(内置对象),x只是“别名”tuple,请参阅下面的内容:

>>> t = tuple
>>> m = t()
>>> type(m)
<type 'tuple'>

答案 4 :(得分:0)

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

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

所有人都会产生<type 'type'>

你可以通过调用as函数来获取这些类型的实例,如下所示:

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

将全部产生<type 'tuple'>

答案 5 :(得分:0)

元组是一个不可变的有序的项目序列。元组的项是任意对象,可以是不同类型的。具有两个(100, 200)项的元组通常称为,而仅包含一个项(3.14,)的元组也称为 singleton

您也可以调用内置类型元组来创建元组。示例:tuple('wow')构建一个等于('w','o','w')的元组。

没有参数的

tuple()创建并返回一个空元组。 和 当x可迭代时,tuple(x)会返回一个元组,其项目与x的项目相同。

这是元组的基本理论。我希望它有助于理解它们。