[英]Python - Partially override method
是否可以部分重写方法? 例如,我的意思是我有一个方法,我想通过一些修改来更新它,但是我不想更改整个方法(我无法弄清楚如何通过继承来更新旧方法,但不能完全更改它)。 所以有可能做这样的事情:
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
类中的定义使用它。 或者,如果我想这样更新,则只有办法重写该方法中的所有内容(因为使用超级方法,我只能得到该方法返回的最终值)?
如建议我用方法更新问题,我尝试仅部分更新它:
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
,插入其他值。
由于tmp
是A
的test
函数的局部变量,因此没有(便携式)访问它的方法。 要么将tmp
用作test
另一个参数,然后传入适当的值(如果没有通过,则可以使用适当的默认值),或者将其设为A
的字段,并在B
覆盖该字段的值。
编辑:看到实际的代码,并得知您不允许对其进行更改,这将使此过程变得更加困难。 基本上,您将必须复制粘贴超类的代码,并仅更改必要的部分。 好的解决方案都需要修改超类的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.