如何将 Nonetype 转换为 int 或 string? [英] How to convert Nonetype to int or string?
问题描述
我有一个 Nonetype
值 x
,它通常是一个数字,但也可以是 None
.我想除以一个数字,但 Python 提出:
I've got an Nonetype
value x
, it's generally a number, but could be None
. I want to divide it by a number, but Python raises:
TypeError: int() argument must be a string or a number, not 'NoneType'
我该如何解决这个问题?
How can I solve this?
推荐答案
在其中一条评论中,您说:
In one of the comments, you say:
不知何故我得到了一个 Nonetype 值,它应该是一个 int,但它现在是一个 Nonetype 对象
Somehow I got an Nonetype value, it supposed to be an int, but it's now a Nonetype object
如果是您的代码,请弄清楚当您期望一个数字时如何获得 None
并阻止这种情况发生.
If it's your code, figure out how you're getting None
when you expect a number and stop that from happening.
如果是别人的代码,找出它给出 None
的条件,并确定一个合理的值,使用通常的条件代码:
If it's someone else's code, find out the conditions under which it gives None
and determine a sensible value to use for that, with the usual conditional code:
result = could_return_none(x)
if result is None:
result = DEFAULT_VALUE
...甚至...
if x == THING_THAT_RESULTS_IN_NONE:
result = DEFAULT_VALUE
else:
result = could_return_none(x) # But it won't return None, because we've restricted the domain.
没有理由在这里自动使用 0
— 依赖于 None
的假"性的解决方案假设您会想要这个.DEFAULT_VALUE
(如果它存在)完全取决于您的代码的用途.
There's no reason to automatically use 0
here — solutions that depend on the "false"-ness of None
assume you will want this. The DEFAULT_VALUE
(if it even exists) completely depends on your code's purpose.
这篇关于如何将 Nonetype 转换为 int 或 string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!