python - python 中类型构造函数的奇怪之处

标签 python constructor

在 python 中我可以做这样的事情:

d = dict()
i = int()
f = float()
l = list()

但是字符串没有构造函数

>>> s = string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'string' is not defined

这是为什么呢?或者,是否有字符串类型的构造函数?

另外,按照上面的定义,

d['a'] = 1

有效,但是

>>> l[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

没有。

有人能给我解释一下吗?

最佳答案

你的意思是:

a = str()

我相信。然后一切正常。

关于d['a']l[0]的区别:d是一个字典,它有一个存储元素的稀疏表示。而列表 (l) 密集地表示数据:所以如果您有:

l = [1,2]

你随后写道:

l[200] = 31

这意味着,除了分配给元素 200 之外,要完全一致,还要在 l[3:199] 中放置一些任意值。

关于python - python 中类型构造函数的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11403046/

相关文章:

python - 如何将字符串作为对象传递给 getattr python

python - 为 20,000 多个更新优化 Sqlite3

c++ - 内置类型的成员是否默认初始化?

java - 使用反射实例化 protected 构造函数时出现 NoSuchMethodException

c++ - g++ 对构造函数的 undefined reference

c++ - 构造函数没有被调用?

Python如何将关系数据放入mongodb+gridfs

python - 如何从 Python 3 中的整数列表创建字节对象

python - 多行正则表达式替换

c++ - 如果更改 const 对象是未定义的行为,那么构造函数和析构函数如何使用写访问权限进行操作?