是否可以部分覆盖方法?我的意思是,例如我有一个方法,我想通过一些修改来更新它,但我不想改变整个方法(我无法弄清楚如何通过继承它来更新旧方法,但不能完全改变它)。所以可以做这样的事情:
class A(object):
def test(self, num):
tmp = 3
res = tmp + num
print
return res
a = A()
a.test(5)
returns 8
class B(A):
def test(self, num):
tmp = 5
a = super(B, self).test(num)
return a
b = B()
b.test(5)
returns 10
有没有办法只更新tmp
值,留下res = tmp + num,因此它将使用它,因为它在A
类中定义。或者,如果我想像这样更新,只有方法可以重写该方法中的所有内容(因为使用super我只得到方法返回的最终值)?
正如所建议我用方法更新问题我尝试仅部分更新它:
def _display_address(self, cr, uid, address, without_company=False, context=None):
'''
The purpose of this function is to build and return an address formatted accordingly to the
standards of the country where it belongs.
:param address: browse record of the res.partner to format
:returns: the address formatted in a display that fit its country habits (or the default ones
if not country is specified)
:rtype: string
'''
# get the information that will be injected into the display format
# get the address format
address_format = address.country_id and address.country_id.address_format or \
"%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
args = {
'state_code': address.state_id and address.state_id.code or '',
'state_name': address.state_id and address.state_id.name or '',
'country_code': address.country_id and address.country_id.code or '',
'country_name': address.country_id and address.country_id.name or '',
'company_name': address.parent_id and address.parent_id.name or '',
}
for field in self._address_fields(cr, uid, context=context):
args[field] = getattr(address, field) or ''
if without_company:
args['company_name'] = ''
elif address.parent_id:
address_format = '%(company_name)s\n' + address_format
return address_format % args
因此,对于此方法,我只需要更新/更改address_format
和args
,插入其他值。
答案 0 :(得分:2)
由于tmp
是A
的{{1}}函数的局部变量,因此没有(便携式)方式来访问它。要使test
的另一个参数tmp
,只需传入适当的值(如果没有传递,则可以使用合适的默认值),或者使其成为test
的字段并覆盖该字段的A
中的值。
编辑:查看实际代码,并了解到您不允许更改它,这使得这更加困难。基本上,您必须复制粘贴超类的代码,只需更改必要的部分。好的解决方案都需要修改超类的方法。