从用户inpu调用module.Functionname

2024-09-29 23:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在用户输入时从图像库调用模块(.)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'


Tags: 用户imageinputpngsavedefopenfilter
1条回答
网友
1楼 · 发布于 2024-09-29 23:25:46

您希望在这里使用getattr

call = getattr(ImageFilter, user_input)
call()

如果代码更明确,可以执行以下操作:

im.filter(getattr(ImageFilter, user_input)()) 

简单的例子:

>>> class Foo:
...     @classmethod
...     def bar(cls):
...         print('hello')
...
>>> getattr(Foo, 'bar')()
hello

但是,您可能希望确保在发送无效内容时处理异常。因此,您可能应该使用try/except来结束调用该方法的尝试

>>> try:
...     getattr(Foo, 'bar')()
... except AttributeError:
...     # do exception handling here

您还可以将默认值指定为None(我个人更愿意(EAFP),然后在调用它之前检查它是否为None

call = getattr(ImageFilter, user_input, None)
if call:
    call()
else:
    # do fail logic here

相关问题 更多 >

    热门问题