Instantiating sub-class from super
> On 14 Oct 2019, at 21:55, DL Neil via Python-list <python-list at python.org> wrote:
> Is there a technique or pattern for taking a (partially-) populated instance of a class, and re-creating it as an instance of one of its sub-classes?
The pattern I know is to use a factory function to choose between a number of concrete classes based on some information.
In this case it seems that after collecting enough information you could create such a class.
The other thought is to have the classes support a method that returns a "better" class.
x = x.upgradeInstance()
I have seen code that messes around with __class__ but I think that its a maintenance issue to do that.
Apart from the person who writes that code would have a clue what it's doing.
> In a medically-oriented situation, we have a Person() class, and start collecting information within an instance (person = Person(), etc).
> During the data-collection process the person's sex may become obvious, eg few males have become/been pregnant.
> We could stick with Person() and implement specific methods therein, rather than separate Man and Woman sub-classes, but...
> It seemed better (at the design-level) to have Man( Person ) and Woman( Person ) sub-classes to contain the pertinent attributes, source more detailed and specific questions, and collect such data; by gender.
> In coding-practice, once gender becomes apparent, how should the instance of the Man() or Woman() sub-class be created - and established with the ID and other attributes previously collected as a Person instance?
> This attempt seems hack-y:
> man = Man()
> man.__dict__.update( person.__dict__ )
> Is there a pythonic tool for such, or is the task outlined fundamentally-inappropriate?