python - 当 if-else 块的两个子句中都存在赋值时,为什么没有为变量赋值?
问题描述
假设我们有类似的东西:
if True:
r = 0
else:
r = 1
print(r)
为什么我们会得到UnboundLocalError: local variable 'r' referenced before assignment
?
实际代码如下所示:
def rasterize_dot_verify_args(callable, parent):
if not hasattr(callable, "__call__"):
raise ValueError()
import inspect
siggy = inspect.signature(callable)
if (len(siggy.parameters) > 1):
raise ValueError()
def rasterize(callable, xparent, make_copy :bool = False):
rasterize_dot_verify_args(callable, xparent)
iparent = xparent
if make_copy:
import copy
iparent = copy.deepcopy(xparent)
if hasattr(iparent, "__iter__"):
in_kids = iter(iparent)
if in_kids != iparent:
lamby = lambda p, *, c=callable: rasterize(c, p)
out_kids = map(lamby, in_kids)
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
r = callable(out_kids) # !!!!!!!!!!!!!!!!!!!!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
else:
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
r = iparent # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return r
import itertools as itts
sixify = lambda obj, *, itts=itts: itts.repeat(obj, 6)
inputs = map(sixify, range(1, 5))
# inputs = (_ for _ in [
# itts.repeat(1, 6),
# itts.repeat(2, 6),
# itts.repeat(3, 6),
# itts.repeat(4, 6)
# ])
print(rasterize(list, inputs))
我不得不在这里添加一点文字,因为“看起来您的帖子主要是代码;请添加更多细节。”
哦,亲爱的....需要更多的文字。
解决方案
r
hasattr(iparent, "__iter__")
当isTrue
和in_kids
!= iparent
is时不会被赋值False
。您应该else
在语句中添加一个块if in_kids != iparent:
来分配r
一个值。
推荐阅读
- html - 如何在 HTML 中创建预期的按钮?
- twitter-bootstrap - 带有滚动内容的 Bootstrap 5 固定高度容器
- matlab - 如何在 matlab 中将 2-D 单元阵列转换为 3-D 单元阵列
- java - 动作不能转换为类 java.lang.String
- autodesk-forge - 如何解释来自 Forge Automation API 的此错误消息?
- android - 当我使用风味时,如何构建原始版本/调试版本?有没有办法为每种口味创建文件夹?& 一次构建所有类型?
- python - 为什么我的可以直接运行的代码添加%timeit后运行失败并提示ValueError?
- flutter - 在 Flutter 中循环遍历列表数据
- laravel - 如何检查 Laravel 查询中哪个条件有数据
- jmeter - JMeter - OutOfMemoryError 如何更改 Jmeter 中的堆大小?