我试图在用户输入时从图像库调用模块(.)functionname。 例如,用户键入 “GaussianBlur”
我希望能够替换(ImagerFilter.user\u input)并调用该过滤器。(第3行)
def ImageFilterUsingPil():
im = Image.open('hotdog.jpg')
im.filter(ImageFilter.GaussianBlur) # instead im.filter(ImageFilter.user_input)
im.save('hotdog.png')
我也试过这个
user_input = 'GaussianBlur'
def ImageFilterUsingPil():
im = Image.open('hotdog.jpg')
im.filter(ImageFilter.user_input)
im.save('hotdog.png')
它把我AttributeError: 'module' object has no attribute 'user_input'
您希望在这里使用getattr
如果代码更明确,可以执行以下操作:
简单的例子:
但是,您可能希望确保在发送无效内容时处理异常。因此,您可能应该使用
try/except
来结束调用该方法的尝试您还可以将默认值指定为
None
(我个人更愿意(EAFP),然后在调用它之前检查它是否为None
:相关问题 更多 >
编程相关推荐