Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么Django IntegerField会在转换为int之前将unicode转换为str?_Python_Django - Fatal编程技术网

Python 为什么Django IntegerField会在转换为int之前将unicode转换为str?

Python 为什么Django IntegerField会在转换为int之前将unicode转换为str?,python,django,Python,Django,我查看了IntegerField的to_python方法。类型转换部分是 try: value = int(str(value)) except (ValueError, TypeError): raise ValidationError(self.error_messages['invalid'], code='invalid') 代码首先将值(键入unicode)转换为str,然后再转换为int。为什么不能直接转换为int,即 try

我查看了
IntegerField
to_python
方法。类型转换部分是

    try:
        value = int(str(value))
    except (ValueError, TypeError):
        raise ValidationError(self.error_messages['invalid'], code='invalid')
代码首先将
(键入unicode)转换为
str
,然后再转换为
int
。为什么不能直接转换为
int
,即

    try:
        value = int(value)
    except...

因为
value
可能是一个对象,而不仅仅是一个字符串文本。调用
str
将强制其字符串表示,而不是
repr
。此外,从Python的禅宗中考虑“显式优于隐式”。Python中的对象被自然地表示为垃圾。它将以类似的形式出现。无法将其转换为整数。表示数字的对象通常具有处理程序,如_uuuUnicode uuur或重写的repr,这些处理程序返回该对象的表示形式。这些通常打印为更合理的值,例如对象的真实值(希望是一个数字)。当然,情况并非总是如此,但对象的str()值通常会给出更接近对象真实值的值。这很难解释,我希望这有帮助!