Take an instance (call it foo) and create a factory class (call it InstanceFactory) that produces foo's. Then inherit from InstanceFactory.
1 2 3 4 5 6 | def MakeClassFromInstance(instance):
from copy import deepcopy
copy = deepcopy(instance.__dict__)
InstanceFactory = type('InstanceFactory', (instance.__class__, ), {})
InstanceFactory.__init__ = lambda self, *args, **kwargs: self.__dict__.update(copy)
return InstanceFactory
|
Perhaps one should warn the users:
this only works with new-style classes
the original per-instance state becomes shared among all instances:
Gabriel, thank you for that comment! While this recipe only applies to new style classes, the original per-instance state is No Longer shared among all instances. Below is a reproduction of your example using the updated recipe. Thanks again, and more discussion + use cases to follow.