Instantiating sub-class from super
Gregory Ewing
greg.ewing at canterbury.ac.nz
Mon Oct 14 18:37:09 EDT 2019
DL Neil 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?
Often you can assign to the __class__ attribute of an instance
to change its class.
Python 3.7.3 (default, Apr 8 2019, 22:20:19)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Person:
... pass
...
>>> class Male(Person):
... pass
...
>>> p = Person()
>>> p.__class__ = Male
>>> isinstance(p, Male)
True
>>>
You would then be responsible for initialising any attributes of
Male that Person didn't have.
--
Greg
More information about the Python-list
mailing list