2015-07-29 1 views
0

Я пытаюсь создать поле, основанное на том, как это было сделано в файле core.py. Но это дает мнеodoo - NameError имя не определено

NameError: name '_amount_all_wrapper' is not defined.

Мой sale.py код:

class SaleOrder(osv.Model): 
_inherit = 'sale.order' 

_columns = { 
    'xx_delivery_date': fields.date(string='Delivery date'), 
    #'xx_payment_method': fields.selection([('visa', 'Visa'), 
    #          ('cash', 'Cash')], 
    #          string='Payment method'), 
    'xx_payment_method': fields.many2one('xx.payment.method', 
             string='Payment method'), 
    'xx_insurance_type': fields.many2one('xx.insurance.type', string='Insurance'), 
    #test to move line 
    'amount_insurance': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Insurance', 
     store={ 
      'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 
      'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), 
     }, 
     multi='sums', help="Amount untaxed plus insurance percentage."), 
} 

def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None): 
    """ Wrapper because of direct method passing as parameter for function fields """ 
    return self._amount_all(cr, uid, ids, field_name, arg, context=context) 

ошибка относится к 'amount_insurance': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Insurance', линии

Поскольку это точно так же, как они сделали, и я не могут найти ссылки на _amount_all_wrapper в своем коде, кроме метода, я действительно не понимаю, что случилось.

ответ

2

Определение _mount_all_wrapper должно существовать, прежде чем вы начнете ссылаться на него. Добавление self не будет работать, поскольку объект не создается, когда эта строка кода выполняется. Yous получал бы эту ошибку даже до выполнения любого кода, в то время как интерпретатор загружает скрипт и создает все определения классов. поэтому необходимо, чтобы объект был определен до фактического ссылки на него.

так просто переместить код вокруг, как это:

class SaleOrder(osv.Model): 
    _inherit = 'sale.order' 

    def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None): 
     """ Wrapper because of direct method passing as parameter for function fields """ 
     return self._amount_all(cr, uid, ids, field_name, arg, context=context) 

    _columns = { 
     'xx_delivery_date': fields.date(string='Delivery date'), 
     #'xx_payment_method': fields.selection([('visa', 'Visa'), 
     #          ('cash', 'Cash')], 
     #          string='Payment method'), 
     'xx_payment_method': fields.many2one('xx.payment.method', 
              string='Payment method'), 
     'xx_insurance_type': fields.many2one('xx.insurance.type', string='Insurance'), 
     #test to move line 
     'amount_insurance': fields.function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Insurance', 
      store={ 
       'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 
       'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty'], 10), 
      }, 
      multi='sums', help="Amount untaxed plus insurance percentage."), 
    } 
+0

Спасибо! Это всегда относится к методам в Python? – ThomasS

+0

не всегда. В определениях внутренней функции вы можете ссылаться на объекты, которые вы будете определять позже. это потому, что объект-объект создается при разборе кода, но его тело не выполняется. но когда вы создаете объект класса, его атрибуты создаются и инициализируются при разборе. Таким образом, любые ссылочные объекты должны быть определены заранее. –