在python开发中使用_defaults和lambda的原因是什么? [英] what is the reason of using _defaults and lambda in python for openerp development?

查看:311
本文介绍了在python开发中使用_defaults和lambda的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习为Python语言开发OpenERP模块。我一直在通过互联网寻找源代码示例,并尝试通过我自己学习。我有bben通过Python代码,不能理解_defaults和lambda的使用。
喜欢:

I have started learning to develop for OpenERP modules under Python language. I have been looking source code examples over internet and try to learn by my own. I have bben going through a Python code and am unable to understand use of _defaults and lambda. Like :

 _defaults = {
        'name': lambda obj, cr, uid, context: '/',
        'state': 'draft',

    }



zpz给了几句话来获得这两个知识。

Plz give a few words to get some know-how on these two .

希望建议

谢谢

推荐答案

_default 字典用于设置其中给出的字段的默认值。在从UI创建任何新记录时,默认情况下将显示此值。

_default dictionary is used for setting defaults values of fields given inside it. This values will be displayed by default while creating any new record from UI.

lambda :Python支持在运行时创建匿名函数(即未绑定到名称的函数),使用一个名为拉姆达。这意味着您可以使用函数运行时,而不用名称定义它,并将其所有代码放在一行中。现在,在OpenERP中,您可以看到这些函数有一些参数,如cr(数据库游标),uid,id等。使用这一切,您可以访问数据库(使用OpenERP的ORM方法)。所以,lambda函数是一个明智的选择,而不是定义整个函数来设置默认值。例如,

lambda : Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This means that you can use a function runtime without defining it with a name, having all its code in a single line. Now, in OpenERP, you can see that functions are having some arguments like cr(database cursor), uid,id etc. Using all this, you can access the database (using OpenERP's ORM methods). So instead of defining a whole function just to set default values, lambda function is a smart choice. For example ,

_defaults = {
    'active': True,
    'type': 'general',
    'company_id': lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
}

在上面的代码中,company_id可以设置为默认使用调用ORM的浏览方法的lambda对于'res.users'类来获取登录用户的id。

In the code above, company_id can be set to default using lambda that calls browse method of ORM for class 'res.users' to get the id of loggedin user.

您可以通过定义一个函数来实现,

You can do it this way also by defining a function,

def _get_default_company(self, cr, uid, context=None):
    company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
    return company_id        
_defaults = {
    'active': True,
    'type': 'general',
    'company_id': _get_default_company,
}

这篇关于在python开发中使用_defaults和lambda的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆