Replace Whole Object Through Object Method

digitalorganics at gmail.com digitalorganics at gmail.com
Mon Jun 26 22:37:39 CEST 2006


Bruno Desthuilliers wrote:
> digitalorganics at gmail.com a écrit :
> > Bruno Desthuilliers wrote:
> (snip)
> >>
> >>Instead of exposing problems with your solution, you may want to expose
> >>the real use case ?
> >
> >
> > I'm working with a team that's doing social modeling, and for example,
> > I need to model workers that at some point in the program may or may
> > not also become employers.
>
> If I understand correctly, only some of the existing workers will become
> employers ?
>
> > Now, I want the workers to take on all
> > behaviors and attributes of an employer in addition to their
> > pre-existing "worker" behaviors and attributes.
>
> wrt/ behaviors, it's easy as pie. Attributes (I mean instance
> attributes) are another problem, but I don't have enough informations to
> deal with this problem here.
>
> > Also, as I'm sure you
> > guessed, the workers' attributes need to retain their values at that
> > point in the program, so a brand new worker-employer object wouldn't in
> > itself do the trick.
>
> Here's a simple stupid possible solution:
>
> class Worker(object):
>    def __init__(self, ...)
>      # init code here
>
>    # behaviours here
>
>    def becomeEmployer(self):
>      self.___class__ = Employer
>
> class Employer(Worker):
>    # behaviours here
>
>
> w = Worker(...)
> w.becomeEmployer()
>
> Note that there's no initializer in the Employer class - it wouldn't get
> called anyway (not automatically at least).

Won't work because there will be employers that aren't workers.
And yes, only some workers will become employers, but also only some
employers will also be workers (at some point in program). Let me be
more clear:

workers
--> subset of workers --become--> employers
employers
--> subset of employers --become--> workers

It is very important that both should maintain attribute values,
regardless of whether they take on new "roles". Furthermore, this is a
very simple case and ultimately in my program an object should be able
to dynamically take on a multitude of roles (classes of behavior)
without mucking at all with their pre-existing states.




More information about the Python-list mailing list