git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Instantiating sub-class from super


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