python - Override the value of a static variable while using decorator -
i've created class following:
class simon: name = 'simon' @classmethod def says(cls, sentence): return '%s says: %s' % (cls.name, sentence)
if want simon sit down, can this:
>>> simon.says('sit down') 'simon says: sit down'
to substitute simon name, say, eva, can subclass this:
class eva(simon): name = 'eva'
and result:
>>> eva.says('stand up') 'eva says: stand up'
now want change says said creating decorator called to_past_tense
:
class eva(simon): name = 'eva' def to_past_tense(self, func): def wrapper(*arg, **kw): present_tense = func(*arg, **kw) past_tense = present_tense.replace('says', 'said') return past_tense return wrapper @classmethod def says(cls, *arg, **kw): return cls.to_past_tense(cls, simon.says)(*arg, **kw)
if this:
>>> eva.says('stand up')
what i'm expecting this:
'eva said: stand up'
but in fact got this
'simon said: stand up'
how can override value?
and, please, me improve title if isn't precise , clear, thank you!
you using simon.says
, retrieving bound class.
if wanted overridden class method have bind current class, use super()
proxy object:
@classmethod def says(cls, *arg, **kw): return cls.to_past_tense(cls, super().says)(*arg, **kw)
the super()
object search mro of class, find says
method on simon
, bind cls
object you, cls.name
value still looked eva
:
>>> class simon: ... name = 'simon' ... @classmethod ... def says(cls, sentence): ... return '%s says: %s' % (cls.name, sentence) ... >>> class eva(simon): ... name = 'eva' ... def to_past_tense(self, func): ... def wrapper(*arg, **kw): ... present_tense = func(*arg, **kw) ... past_tense = present_tense.replace('says', 'said') ... return past_tense ... return wrapper ... @classmethod ... def says(cls, *arg, **kw): ... return cls.to_past_tense(cls, super().says)(*arg, **kw) ... >>> eva.says('hello') 'eva said: hello'
Comments
Post a Comment