简体   繁体   English

将方法名称作为函数参数传递

[英]Passing method name as function argument

I'm probably missing something obvious here, what I'm trying to do is extract part of this Django view into a function since I'm using same code multiple times: 我可能在这里缺少明显的东西,我想做的是将这个Django视图的一部分提取到一个函数中,因为我多次使用相同的代码:

def method_name(pk, method_name, model_name):
    instance = get_object_or_404(Document, id=pk)
    wb = instance.method_name()
    with NamedTemporaryFile() as tmp:
        wb.save(tmp.name)
        tmp.seek(0)
        stream = tmp.read()
    instance.model_name.save('POPDV.xlsx', ContentFile(stream), save=False)
    instance.save()

I would like to pass model_name as a method name (in bold). 我想将model_name传递为方法名称(粗体)。 What is the correct way to do this? 正确的方法是什么? My solution would be calling instance.__getattribute__ ("model_name").save(...) 我的解决方案是调用instance.__getattribute__ ("model_name").save(...)

You can use getattr to access attributes by name: 您可以使用getattr按名称访问属性:

wb = getattr(instance, method_name)()
# ...
getattr(instance, model_name).save(...)

getattr(obj, name) implicitly goes through the various attribute lookup options: obj.__getattribute__(name) , obj.__dict__['name'] , obj.__getattr__(name) getattr(obj, name)隐式地通过各种属性查找选项: obj.__getattribute__(name)obj.__dict__['name']obj.__getattr__(name)

Usually, you do not call magic methods directly. 通常,您不直接调用魔术方法。 They often are hooks for built-in methods or operators, eg iter(obj) calls obj.__iter__() , len(obj) calls obj.__len__() . 它们通常是内置方法或运算符的钩子,例如iter(obj)调用obj.__iter__()len(obj)调用obj.__len__()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM