ODOO12图书项目继承Python方法

it2025-03-15  23

Python 方法中编写的业务逻辑也可以被继承。Odoo 借用了 Python 已有的父类行为的对象继承机制。 作为一个实际的例子,我们将继承图书 ISBN 验证逻辑。在图书应用中仅能验证13位的 ISBN,但老一些的图书可能只有10位数的 ISBN。我们将继承_check_isbn()方法来完成这种情况的验证。在library_member/models/library_book.py文件中添加如下方法:

from odoo import api, fields, models class Book(models.Model): _inherit = 'library.book' is_available = fields.Boolean('Is Available?', readonly=False) @api.multi def _check_isbn(self): self.ensure_one() isbn = self.isbn.replace('-','') digits = [int(x) for x in self.isbn if x.isdigit()] if len(digits) == 10: ponderators = [1, 2, 3, 4, 5, 6, 7, 8, 9] total = sum(a * b for a, b in zip(digits[:9], ponderators)) check = total % 11 return digits[-1] == check else: return super()._check_isbn()

要继承方法,我们要重新定义该方法,可以使用 super()来调用已实现的部分。在这个方法中我们验证是否为10位数 ISBN,然后插入遗失的验证逻辑。若不是10位,则进入原有的13位验证逻辑。 在扩展之前10位ISBN是不支持的,直接报是错误的ISBN号 扩展之后能够正常识别10位的ISBN号。 演示视频: http://www.tderp.com/download/details/odoo12python-863

http://ctdrive.tderp.com/file/13502532-467683657

最新回复(0)