On 2012-10-04 12:08, Manlio Perillo wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Il 03/10/2012 22:38, Simone Federici ha scritto:
2012/10/3 Manlio Perillo <manlio.peri...@gmail.com
<mailto:manlio.peri...@gmail.com>>

    Infatti ho risposto a Daniele che parlava di web server.


me tapino :-D
avevo frainteso.

per tornare al topic iniziale,
io il cambio di classe delle istanze lo considero normalissimo,
ho codice in produzione che fa le magie


Che sia un pattern normale lo dimostra il fatto che sia supportato anche
in CLOS (Common Lisp) tramite make-instance-obsolete e
update-instance-for-redefined-class.

Con CLOS c'รจ proprio il supporto per gestire il caso di una classe che
viene ridefinita e tutte le sue instance devono essere aggiornate.

Tanto per continuare l'hack, e sempre col disclaimer che se esistesse un'ortodossia in Python questo potrebbe non farne parte: in quest'esempio una classe viene ricaricata e tutte le sue istanze "corrette" facendole puntare alla nuova classe.

In [1]: open("testmod.py", "w").write("class C(object):\n def f(self):\n return 10")

    In [3]: import testmod

    In [4]: c = testmod.C()

    In [5]: c.f()
    Out[5]: 10

In [6]: open("testmod.py", "w").write("class C(object):\n def f(self):\n return 20")

    In [7]: oldcls = testmod.C

    In [8]: reload(testmod)
    Out[8]: <module 'testmod' from 'testmod.py'>

    In [9]: newcls = testmod.C

    In [10]: newcls is oldcls
    Out[10]: False

    In [11]: c.f()
    Out[11]: 10

    In [12]: import gc

    In [14]: id(c)
    Out[14]: 43878544

    In [15]: for o in gc.get_objects():
       ....:     if isinstance(o, oldcls):
       ....:         print id(o)
       ....:         o.__class__ = newcls
       ....:
       ....:
    43878544

    In [16]: c.f()
    Out[16]: 20


--
Daniele Varrazzo - Develer S.r.l.
http://www.develer.com
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python

Rispondere a