Changing the class of an instance
Huaiyu Zhu
hzhu at localhost.localdomain
Thu Jul 13 15:05:38 EDT 2000
On 13 Jul 2000 01:02:15 +0200, Bernhard Herzog <herzog at online.de> wrote:
>In this case I think a factory function would be much cleaner:
>
>def instantiate(data):
> if data is something:
> return Special1(data)
> else:
> return Special2(data)
>
>Putting knowledge about what derived classes exist into the base class
>is the wrong approach, IMO. You obviously have to have knowledge about
>the derived classes somewhere in the code, and the right place for that
>is a factory function or something similar outside of the class
>hierarchy.
>
In the examples I have in mind, most knowledge about the data is held in the
base class. The derived classes only override a few method in applications.
So I suppose your suggestion would be like
def instantiate(data):
General.preprocess(data)
if General.someproperty(data):
return Special1(data)
else:
return Special2(data)
Yes, it looks cleaner because there will not be any issue with overrided
__init__ or the like.
Several others have said that in this case there is no need to have the base
class. Of course this is only true of the example, but not of the real
situation from which it's abstracted.
Huaiyu
More information about the Python-list
mailing list