Ho due classi (chiamiamole Working and ReturnStatement) che non posso modificare, ma voglio estenderle entrambe con il logging. Il trucco è che il metodo Working restituisce un oggetto ReturnStatement, quindi il nuovo oggetto MutantWorking restituisce anche ReturnStatement a meno che non possa lanciarlo su MutantReturnStatement. Dire con il codice:Come eseguire il cast dell'oggetto in Python
# these classes can't be changed
class ReturnStatement(object):
def act(self):
print "I'm a ReturnStatement."
class Working(object):
def do(self):
print "I am Working."
return ReturnStatement()
# these classes should wrap the original ones
class MutantReturnStatement(ReturnStatement):
def act(self):
print "I'm wrapping ReturnStatement."
return ReturnStatement().act()
class MutantWorking(Working):
def do(self):
print "I am wrapping Working."
# !!! this is not working, I'd need that casting working !!!
return (MutantReturnStatement) Working().do()
rs = MutantWorking().do() #I can use MutantWorking just like Working
print "--" # just to separate output
rs.act() #this must be MutantReturnState.act(), I need the overloaded method
Il risultato atteso:
sto avvolgendo di lavoro.
Sto lavorando.
-
Sto avvolgendo ReturnStatement.
Sono un ReturnStatement.
È possibile risolvere il problema? Sono anche curioso di sapere se il problema può essere risolto anche in PHP. A meno che non ottenga una soluzione funzionante, non posso accettare la risposta, quindi per favore scrivi un codice funzionante per essere accettato.
"Casting" non esiste in Python. –
Inoltre, non dovresti eseguire "' ReturnStatement(). Act() '" - se vuoi che il metodo act attivi sull'altra classe per lavorare sull'oggetto corrente, esegui 'returnStatement.act (self)' - o semplicemente contrassegnalo come classmethod o staticmethod - se non ha bisogno di un'istanza dell'oggetto corrente. – jsbueno
Working.do() restituisce con ReturnStatement. Voglio MutantWorking.do() per tornare con un MutantReturnStatement. So che il casting non esiste in Python, ma il problema esiste. C'è una soluzione? – Visko